Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Validating input for textbox on winforms

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.

like image 745
Rocshy Avatar asked Jan 18 '12 18:01

Rocshy


1 Answers

Description

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

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e) {     if (textBox1.Text != "something")         e.Cancel = true; } 

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

  • MSDN - Control.Validating Event
  • MSDN - ErrorProvider Component (Windows Forms)
  • Using Error Provider Control in Windows Forms and C#
like image 141
dknaack Avatar answered Sep 20 '22 06:09

dknaack