I would like to create a TextBox that allows users to key in decimal values. Now the catch is, I want to give maxlength to the integral part(value before decimal) so when i say the maxlength is 5
User can enter
.12
12345
12345.67
User should not be able to enter
123456
123456.78
I am handling the textbox keypress to restrict the alphabets
If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> "."c Then
e.Handled = True
End If
' only allow one decimal point
If e.KeyChar = "."c AndAlso TryCast(sender, TextBox).Text.IndexOf("."c) > -1 Then
e.Handled = True
End If
Can somebody please help me with this maxlength part. Appreciate any help and directions.
You won’t be able to do this with the
MaxLengthproperty, the text box is simply looking atString.Length, whereas what you want is to actually parse the string into a decimal value and do some bounds checking on it.You will need to do that in your key press event. The simplest thing to do would be to do something like:
That’s not the exact algorithm you probably want, but you get the idea.