Harambe Harambe - 1 year ago 65
Vb.net Question

Validate TextBox input at caret location

I've got the following code to format decimal input into a

TextBox
.

If Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "."c Then
If e.KeyChar = "."c Then
If txtPrice.Text.Contains("."c) Then
e.Handled = True
End If
ElseIf Char.IsDigit(e.KeyChar) Then
If txtPrice.Text.Contains("."c) Then
Dim value As String = txtPrice.Text
Dim units As String = value.Substring(value.IndexOf("."c) + 1)

If units.Length >= 2 Then
e.Handled = True
End If
End If
End If
ElseIf e.KeyChar <> Chr(8) Then
e.Handled = True
End If


This all works fine, however, if I enter a value into the
TextBox
, e.g. 10.50 , when I then try to just delete the first 0 and change the value to 11.50, it won't allow me to, as there are 2 digits after the decimal point which cancels all other user input, to ensure that only 2 decimal places can be entered.

Is there a way that I can validate this to check if the digit is being added before or after the decimal point? Or if it can check it based on the caret location?

There is probably an easier way to validate decimal in a
TestBox
, however this code is also used for validating grids and other controls, so something in this format is needed.

Answer Source

Check the SelectionStart property.

If units.Length >= 2 AndAlso txtPrice.SelectionStart > txtPrice.Text.IndexOf(".") Then
    e.Handled = True
End If

Above code explained:

If text already 2 characters after the . you're trying to add another, prevent keypress. If adding before the . then allow.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download