TextBox validation.

G

Guest

I have a text box (several actually) that I need to validate. Some of the
conditions is that it can't be empty, it can only contain numeric characters
and optionally dashes, etc. One of the problems is that once a user has
started entering text in this text box, unless it is valid input focus stays
on that control. I would like for there to be a way for the user to "get out"
of the control. Typically I would expect that hitting <ESC> would do that but
I don't see an event like for DataGridView where there is a CellEndEdit event
for a text box. Another problem is that if the user hits <ENTER>, notihing
happens. Again I would expect for the validating event to fire but it
doesn't. Is there a more robust way of validating text box input?

Thank you.

Kevin
 
G

Guest

The focus is not "forced" to stay in the textbox, if you do not set e.Cancel
= True in its Validating event handler. So, leave that away from the event
handler and it will
be possible to move the focus from one control to another, even with invalid
data.

You can still use an errorprovider to inform the user of the bad data.

As for the Esc and Enter key behaviours, try the foloowing:

Private _prevTextBox1Value As String

Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As
System.EventArgs) Handles TextBox1.Enter
_prevTextBox1Value = TextBox1.Text
End Sub

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Escape Then
TextBox1.Text = _prevTextBox1Value
End If
End Sub

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = vbCr Then
SendKeys.Send("{Tab}")
e.Handled = True
End If
End Sub

Hope this helps,

Joris
 
S

Stoitcho Goutsev \(100\)

Kevin,

I understand your are using .NET2.0 because you mentioned DataGridView
controls. In this case don't you use the MaskedTextBox control? This way you
can prevent users of making mistakes instead of showing them error messages
for wrong input.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top