Posted By

pckujawa on 11/03/09


Tagged

validation WinForms


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

khouser


User input validation in Visual Studio .NET using MaskedTextBoxes and an ErrorProvider


 / Published in: C#
 

I just discovered that the MaskedTextBox control allows you to set the type of data which should be entered in the control and helps you do the validation of that data when necessary. The trick is to set the ValidatingType of the MaskedTextBox control to the type of data you want to get from the user. If you do this, as well as subscribe to the TypeValidationCompleted event, on the form Load event, you can handle user validation inside your TypeValidationCompleted event handler.

If you want to read about the MaskedTextBox, it's all on MSDN. What you should be aware of, though, is that the Mask is not required. When the mask is blank, you can accept input just like you can with a TextBox.

The ErrorProvider is a WinForms control that allows you to show a red exclamation mark with an error message tooltip next to a control. It's really useful when combined with the above data validation method.

The example shows us setting the type of data which should be entered into the text box and then subscribing to the corresponding event. In that event handler, we check if the input is valid (don't know what all that does, but it works - play with it) and, if so, cast the value to the correct data type in order to use for some purpose. We also clear any errors in the ErrorProvider (not sure of the best way to use this control, but this works). If the input is not valid, we set the error shown by the ErrorProvider (the e.Message is generally the same as the Message parameter of any exception that has been thrown). (You can set the error to the control by name, or generically by using the sender argument.)

  1. private void PrimaryForm_Load(object sender, EventArgs e)
  2. {
  3. maskedTextBox1.ValidatingType = typeof (int);
  4. maskedTextBox1.TypeValidationCompleted +=
  5. maskedTextBox1_TypeValidationCompleted;
  6. }
  7.  
  8. void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
  9. {
  10. MessageBox.Show("maskedTextBox1_TypeValidationCompleted");
  11. if (e.IsValidInput)
  12. {
  13. var intInput = (int)e.ReturnValue;
  14. // Do something
  15. errorProvider.Clear();
  16. }
  17. else
  18. {
  19. errorProvider.SetError((Control)sender, e.Message);
  20. //errorProvider.SetError(maskedTextBox1, e.Message);
  21. }
  22. }

Report this snippet  

You need to login to post a comment.