允许文本框vb中的负数和正数

问题描述 投票:-1回答:2

我有一个问题,我需要在文本框中的按键事件中,只需输入caracter( - )和数字

例如:-540612或64346

文本框允许负数和正数

textbox
2个回答
0
投票
Private Sub txtMonRenta_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtMonRenta.KeyPress
    If Not IsNumeric(e.KeyChar) AndAlso System.Convert.ToByte(e.KeyChar) <> 8 AndAlso Convert.ToByte(e.KeyChar) <> 45 Then
        e.Handled = True
    End If
End Sub

这项工作很好!!


0
投票

这类问题有很多“答案”,经过审查后,我找到了一种简单直接的方法。这是我打电话的子项:

  Private Sub txtNumOnly_KeyPress(sender As Object, e As KeyPressEventArgs, txtBox As TextBox)

  'If not backspace or acceptable char flush key
  If (Not e.KeyChar = ChrW(Keys.Back) And ("0123456789.-").IndexOf(e.KeyChar) = -1) Then
    e.Handled = True
  End If

  'Only one decimal allowed
  If (e.KeyChar = "." And txtBox.Text.ToCharArray().Count(Function(c) c = ".") > 0) Then
    e.Handled = True
  End If

  'Deal with selected text too.
  If txtBox.SelectionLength > 0 Then
    If txtBox.Text.Length <> txtBox.SelectionLength Then
      If e.KeyChar = "-" Then 
        e.Handled = True
        Exit Sub 'avoid other checks, we're done
      End If 'e.KeyChar = "-"
    Else ''txtBox.Text.Length <> txtBox.SelectionLength
      Exit Sub 'allow it, all text is replaced
    End If 'txtBox.Text.Length <> txtBox.SelectionLength
  End If 'txtBox.SelectionLength > 0

  'Only one minus allowed and must be first char
  If (e.KeyChar = "-" And txtBox.Text.ToCharArray().Count(Function(c) c = "-") > 0) Then
    e.Handled = True
  End If

  If e.KeyChar = "-" And txtBox.Text.Length > 0 Then
    e.Handled = True
  End If

End Sub

现在在文本框的KeyPress事件处理程序中:

  Private Sub txtDaysReview_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtDaysReview.KeyPress
    txtNumOnly_KeyPress(sender, e, txtDaysReview) '<==Adjust the txtDaysReview to reference the TextBox being checked
  End Sub
© www.soinside.com 2019 - 2024. All rights reserved.