验证多个文本框

时间:2011-02-23 06:50:03

标签: c# .net winforms validation textbox

我正在创建一个C#窗口应用程序,其中我已经取了10个文本框。我想验证每个文本框意味着没有文本框应该是空白的。我已经使用errorprovider控件进行验证,点击提交按钮。 代码正常工作,但我想在空白文本框中插入值后立即删除错误提供程序通知。如何可能请通过任何示例给我代码。

提前致谢。

4 个答案:

答案 0 :(得分:1)

执行此操作的正确方法是为每个TextBox控件处理Validating event。对于您描述的方案,似乎没有任何理由同时使用ValidatingValidated

因此,正如Vinay建议的那样,最好要做的事情是将此代码封装到一个继承自内置TextBox的自定义控件中。覆盖自定义控件的OnValidating method并放置验证逻辑,用于设置/清除ErrorProvider。然后使用自定义类的实例替换表单上的每个文本框控件,而不是内置的。

如果确实希望在文本框中输入文本时更新验证状态,则需要处理TextChanged事件并调用验证代码来设置/清除ErrorProvider。覆盖自定义控件中的OnTextChanged method即可执行此操作。

答案 1 :(得分:1)

这是我使用的代码。您可以看到有2个处理程序,一个用于验证,第二个用于TextChanged事件。 DataTextBox在Toolbox中显示为一个图标,因此您可以通过鼠标放置它,您也可以在属性窗口中设置canBeEmpty属性,默认值为true。

public class DataTextBox:TextBox
{
    public DataTextBox()
    {
        this._errorProvider2 = new System.Windows.Forms.ErrorProvider();
        //this.errorProvider1.BlinkRate = 1000;
        this._errorProvider2.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;

        this.TextChanged+=new EventHandler(dtb_TextChanged);
        this.Validating += new System.ComponentModel.CancelEventHandler(this.dtb_Validating);


    }
    private ErrorProvider _errorProvider2;

    private Boolean _canBeEmpty=true;
    public Boolean canBeEmpty
    {
        get { return (_canBeEmpty); }
        set { _canBeEmpty = value; }
    }

    private void dtb_Validating(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if ((this.Text.Trim().Length == 0) & !this.canBeEmpty)
        {
            _errorProvider2.SetError(this, "This field cannot be empty.");
            e.Cancel = true;
        }
        else
        {
            _errorProvider2.SetError(this, "");
            e.Cancel = false;
        }
    }

    private void dtb_TextChanged(object sender, EventArgs e)
    {
        if (this.Text.Trim().Length != 0) _errorProvider2.SetError(this, "");
        else _errorProvider2.SetError(this, "This field cannot be empty.");
    }
}

}

答案 2 :(得分:0)

根据您的实现,在文本框更改事件中,您可以调用文本框验证/验证事件处理程序,它将根据您在验证/验证处理程序中实现的任何逻辑设置或清除错误。

答案 3 :(得分:0)

通常,当焦点离开文本框时,验证应该发生 - 您的验证事件是否在此处被触发?请参阅this MSDN documentation中的示例部分,了解如何结合使用验证和验证事件来实现此目的。

由于你有很多这样的文本框,我建议你在里面创建自定义文本框控件封装验证逻辑。

相关问题