获取按键事件中文本框的全文

时间:2012-05-11 17:55:46

标签: vb.net keypress

这是我的代码:

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"

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

2 个答案:

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

答案 1 :(得分:1)

实际上,它有点复杂 - 比如用户按下退格键怎么办?您可能最好建议使用TextChanged事件,该事件在按下最后一个键更新Text属性后触发。

相关问题