0

这是我的代码:

Private Sub prices_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles wholeprice_input_new_item.KeyPress, dozenprice_input_new_item.KeyPress, detailprice_input_new_item.KeyPress, costprice_input_new_item.KeyPress

        Dim TxtB As TextBox = CType(sender, TextBox)
        Dim rex As Regex = New Regex("^[0-9]*[.]{0,1}[0-9]{0,1}$")

        'MsgBox(TxtB.Text())    

        If (Char.IsDigit(e.KeyChar) Or e.KeyChar.ToString() = "." Or e.KeyChar = CChar(ChrW(Keys.Back))) Then
            If (TxtB.Text.Trim() <> "") Then
                If (rex.IsMatch(TxtB.Text) = False And e.KeyChar <> CChar(ChrW(Keys.Back))) Then
                    e.Handled = True
                End If
            End If
        Else
            e.Handled = True
        End If

    End Sub

文本框的 Text 属性不包括最后按下的字符,例如:

 Text entered = "12.1"
 TxtB.Text = "12."

 Text entered = "11.."
 TxtB.Text = "11."

 Text entered = "12"
 TxtB.Text = "1"

我想验证所有字符。如何使事件按键验证文本框中的所有字符?

4

2 回答 2

1

问题是在 KeyPress 事件中,正在按下的键尚未添加到文本框中。您可以将按下的字符添加到现有文本中,如下所示:

Dim TxtB As TextBox = CType(sender, TextBox)
If (Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "."c Then
    Dim fullText As String = TxtB.Text & e.KeyChar
    'Do validation with fullText
End If
于 2012-05-11T21:40:45.660 回答
1

实际上,它比这更复杂一些——例如,如果用户按下退格键会怎样?最好建议您改用 TextChanged 事件,该事件在 Text 属性被最后一次按下的键更新后触发。

于 2012-06-22T14:56:14.180 回答