.NET ‘Validating’ event and ‘ErrorProvider’ class
Posted by admin on 29th August 2006
Found this little gem while looking to constrain textbox input to numeric.
It works by constructing an ErrorProvider instance in the container form, and then specifying and setting validation states during the ‘validating’ and ‘validated’ messages sent from the control. ErrorProvider is a generally available class that signals the error by flashing an icon next to the control with the offending input
It has some interesting points – ErrorProvider can be used in anything, not just textboxes. It locks focus and input to the control until you correct the input, and puts up a little blinking icon (which you can specify), to draw your attention to the offending input
Not quite the same as the Qt validator mechanism. I think Qt’s is better in that invalid input is suppressed by the supplied filter and won’t echo (it’s filtered out), however, it is very specific to textboxes.
In .NET, the invalid input is still echoed and the invalid state isn’t flagged until you move focus off the offending control. There may be a way around that (to provide a keystroke filtering behavior), but the standard implementation doesn’t appear to provide for it, that I can see.
Under the ErrorProvider topic in the MS documentation, there’s a lengthy example. You can reduce it to the following though (to restrict input in a textbox to numeric, for example):
private Textbox inputTB;
private ErrorProvider numberInputErrorProvider;
private Regex regxNumeric;
// declare these somewhere in your class...
// the regular expression is used to qualify the validation.
...
...
numberInputErrorProvider = new ErrorProvider();
// create in the constructor of your *container* class
regxNumeric = new Regex("^[0-9]*(\.[0-9]*){0,1}$");
// ditto this - keeps it from having to be re-compiled
// on every invocation.
inputTB = new Textbox();
inputTB.Validating += new
System.ComponentModel.CancelEventHandler(NumericTB_Validating);
inputTB.Validated += new EventHandler(inlineFilterTB_Validated);
// set up the textbox and add the event handlers.
...
...
// gets called on focus loss
//
private void inputTB_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
TextBox tb = sender as TextBox;
if (! regxNumeric.IsMatch(tb.Text)) // this is the test against the textbox text
{
e.Cancel = true;
numberInputErrorProvider.SetError(tb, "Input must be numeric.");
// this sets the error
}
}
// Don't forget to add this!! You need it to clear the error...
//
private void inputTB_Validated(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
numberInputErrorProvider.SetError(tb, "");
}
And, that’s pretty much all there is to it.
Posted in .NET, CSharp, Programming | No Comments »
