codeGEN
codeGEN

Reputation: 714

VB.Net get text after keypress

I am running some custom validations on textbox keypress event.

When a user presses a key I want to find out the text that would exist after that particular key press.

Eg. If the textbox currently contains 12.4 and the user press "6" key I want to find out what the text would be afterwards. I tried appending the e.KeyChar to the end of the textbox.text but there would be problems if the user highlights portions of the textbox and then press a key.

Is there anyway to detect the actual value that would exist after a key has been pressed?

Upvotes: 1

Views: 2973

Answers (1)

LarsTech
LarsTech

Reputation: 81620

You would have to disassemble the current text based on the current caret position, examine the incoming text, and then reassemble the text again:

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
                                                Handles TextBox1.KeyPress
  Dim part1 As String = TextBox1.Text.Substring(0, TextBox1.SelectionStart)
  Dim part2 As String = TextBox1.Text.Substring(TextBox1.SelectionStart + _
                                                TextBox1.SelectionLength)
  Dim character As String = String.Empty
  If Char.IsDigit(e.KeyChar) Then
    character = e.KeyChar.ToString
    Dim result As String = part1 & character & part2
    'Do something with result...
  Else
    e.Handled = True
  End If
End Sub

Upvotes: 1

Related Questions