I want to check what the user is writing in a textbox before I save it in a database. What is the best way to do this? I guess I can always write some ifs or some try-catch blocks, but I was wondering if there's a better method. I've read something about Validating Events, but I am not sure how can I use them.
There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating
event.
The Validating
event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true
the TextBox doesn't lose the focus.
MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order
Enter
GotFocus
Leave
Validating
Validated
LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
private void textBox1_Validating(object sender, CancelEventArgs e) { if (textBox1.Text != "something") e.Cancel = true; }
You can use the ErrorProvider
to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With