Checking that TextBox.Text.Length is between 1 and 10
Firstly, don't call Focus
. The documentation clearly states, don't call Focus
. If you want to focus a control, you call its Select
method.
You don't need to call either though. You should be handling the Validating
event and if the control fails validation, you set e.Cancel
to True
and the control will not lose focus in the first place.
If myTextBox.TextLength < 1 OrElse myTextBox.TextLength > 10 Then
'Validation failed.
myTextBox.SelectAll()
e.Cancel = True
End If
TM80
Updated on June 04, 2022Comments
-
TM80 almost 2 years
I am trying to validate the number of characters placed inside a
TextBox
but am having some trouble. The code I'm using is as follows:If Not ((TextBox5.Text.Length) <= 1) Or ((TextBox5.Text.Length) >= 10) Then MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.") TextBox5.Focus() TextBox5.SelectAll() Else 'do whatever End If
What I want is for
TextBox5
to have a length between (and inclusive) 1 and 10, if not reselect theTextBox
making it ready for another user input.The code responds well for an input less than 1 but fails to recognise any input larger than 10 characters. I can't see what i'm doing wrong?