John Nuñez
John Nuñez

Reputation: 1830

Get the full text of a textbox in a keypress event

This is my code:

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

The textbox's Text property doesn't include the last character pressed, example:

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

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

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

I want to validate all the characters. How I can make the event keypress validate all characters in a text box?

Upvotes: 0

Views: 5677

Answers (2)

John Warner
John Warner

Reputation: 11

Actually, it's a little more complicated than that - what if the user pressed the backspace key, for instance? You might be better advised to use the TextChanged event instead, which fires after the Text property has been updated by the last key pressed.

Upvotes: 1

Meta-Knight
Meta-Knight

Reputation: 17855

The problem is that in the KeyPress event, the key that's being pressed is not yet added to the textbox. You could add the character that's being pressed to the existing text, something like this:

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

Upvotes: 1

Related Questions