0

我有一个 Windows 窗体应用程序并正在调用ErrorProvider.Dispose以清除错误文本。但是,当我第二次调用它时它不起作用(即,如果文本框为空,ErrorProvider则会显示,但在我填充文本框并再次按下提交按钮后,它不会显示错误)。

我有一个包含许多文本框的表单,我只是在单击提交按钮后检查字段是否为空:

foreach (Control c in this.college.Controls)
{
    if (c is TextBox)
    {
        TextBox textBox = c as TextBox;
        if (textBox.Text.Equals(string.Empty))
        {
            if (string.IsNullOrWhiteSpace(textBox.Text))
            {
                errorProvider1.SetError(textBox, "Field Empty");
            }
            else
            {
                errorProvider1.Dispose();
            }
        }
    }
}
4

3 回答 3

1

如果您的意图只是清除先前的错误消息,则只需再次调用 SetError 方法,但传入一个空字符串。

if (string.IsNullOrWhiteSpace(textBox.Text)) 
{ 
    errorProvider1.SetError(textBox, "Field Empty"); 
} 
else 
{ 
    errorProvider1.SetError(textBox, string.Empty); 
} 

无需调用 Dispose()。相反,调用 Dispose 将破坏 errorprovider,并且在表单的剩余生命周期中将无法使用。

于 2012-07-24T14:15:36.723 回答
0

我认为您的代码永远不会达到

errorProvider1.Dispose()

由于 if 语句

if (textBox.Text.Equals(string.Empty))

做第二个 if 语句

if (string.IsNullOrWhiteSpace(textBox.Text))

无用。

如果 textBox.Text 为空,则它也是 null-or-whitespace。

于 2012-07-24T14:18:35.170 回答
0

您不想在错误提供程序上调用 .Dispose() - 这将由垃圾收集器自动收集。您的代码应该如下所示:

   foreach (Control c in this.college.Controls)
    {

        if (c is TextBox)
        {

            TextBox textBox = c as TextBox;


             if (string.IsNullOrWhiteSpace(textBox.Text))
             {
                errorProvider1.SetError(textBox, "Field Empty");
             }
             else
             {
                errorProvider1.SetError(textBox, "");
             }
        }
    }
于 2012-07-24T14:19:30.410 回答