1

第一次发帖!我是 C# 和 errorProvider 的新手。我一直在寻找使用 errorProvider 的最佳实践。我找到了以下代码:

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, "");
}

我没有处理 Validated 事件,而是简单地在进入 Validating 事件的过程中清除错误,并让错误在该事件处理程序中再次设置,如下所示:

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;
}

我的验证比这更复杂,我有几个地方需要清除。我的背景是这种技术很常见的嵌入式代码。

处理 Validated 事件是更好的做法吗?谢谢。

4

0 回答 0