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

时间:2016-12-22 14:37:58

标签: textbox

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

示例:-540612或64346

文本框允许负数和正数

2 个答案:

答案 0 :(得分: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

这项工作很好!!

答案 1 :(得分:0)

有很多&#34;答案&#34;对于这类问题,经过审查,我发现了一种简单直接的处理方法。以下是我打电话的内容:

  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