1

First post! I am new to C# and errorProvider. I was looking around for best practices in using errorProvider. I found the following code:

void TextBox_Validating( object sender, CancelEventArgs e ) {
    TextBox textBox = sender as TextBox;

    bool valid = textBox.TabIndex == 1 || textBox.Text.Length > 0;

    if( !valid )
        m_ErrorProvider.SetError( textBox, "Error " + textBox.Name );

    e.Cancel = !valid;
}

private void TextBox_Validated(object sender, System.EventArgs e) {
    TextBox textBox = sender as TextBox;
    m_ErrorProvider.SetError(textBox, "");
}

Instead of handling the Validated event, I have been simply clearing the error on the way into the Validating event and letting the error get set again in that event handler as follows:

void TextBox_Validating( object sender, CancelEventArgs e ) {
    TextBox textBox = sender as TextBox;

    m_ErrorProvider.SetError(textBox, "");

    bool valid = textBox.TabIndex == 1 || textBox.Text.Length > 0;

    if( !valid )
        m_ErrorProvider.SetError( textBox, "Error " + textBox.Name );

    e.Cancel = !valid;
}

My validation is more complex than this where I have several places that it would be cleared. And my background is embedded code where this technique is common.

Is handling the Validated event better practice? Thanks.

bgrupczy
  • 67
  • 1
  • 2
  • 8
  • 1
    It's OK. You can take a look at [this aswer](http://stackoverflow.com/a/33080822/3110834). Also you can consider implementing [IDataErrorInfo](https://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo(v=vs.110).aspx) for your model classes. Also you may find this msdn article helpful: [Extending Windows Forms with a Custom Validation Component Library](https://msdn.microsoft.com/en-us/library/ms950965.aspx) – Reza Aghaei Dec 04 '15 at 05:22

0 Answers0