Reputation: 123
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 the TextBox
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?
Upvotes: 2
Views: 19538
Reputation: 61
There are 2 things you must do:
like this:
Private Sub res_pin_KeyPress(sender As Object, e As KeyPressEventArgs) Handles res_pin.KeyPress
If e.KeyChar = Chr(13) Then
If Me.res_pin.Text.Length < 6 Then
e.Handled = True
Else
Me.res_deposit.Focus()
End If
End If
End Sub
Upvotes: 0
Reputation: 996
From what I can understand, this should do the trick.
NOTE There are a few different ways to achieve this task, however from there sample code you have shown, this should be fine.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox5.Text.Length < 1 Or TextBox5.Text.Length > 10 Then
MsgBox("Invalid date entry. Use the the following format: DD-MM-YYYY.")
TextBox1.SelectAll()
Else
MessageBox.Show("date accepted...")
End If
End Sub
I have this triggering from a button click event.
Upvotes: 0
Reputation: 54417
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
Upvotes: 3