问题描述
private void tbxWidthBackIamge_Validated(object sender, EventArgs e)
{
this.errBackWidth.SetError(tbxWidthBackIamge, "Enter the Width");
if (tbxBackImage.Text != "")
this.errBackHeight.Dispose();
}
我使用errorProvider验证文本框.发生错误时显示.但是在更正错误后,它并没有消失.
I use an errorProvider to validate a textbox. It appears when there occurred an error. But It didn''t disappear after correct the error. Is any error in this code?
推荐答案
- 使用Validat ing 事件
- 在输入不正确时使用SetError(...,"ErrorMessage")
- 使用SetError(.. .,string.Empty)输入正确时
- Use the Validating event
- Use SetError(..., "ErrorMessage") when the input is incorrect
- Use SetError(..., string.Empty) when the input is correct
private void tbxWidthBackIamge_Validated(object sender, EventArgs e) {
if (tbxBackImage.Text.Trim() == string.Empty)
this.errBackWidth.SetError(tbxWidthBackIamge, "Enter the Width");
else
this.errBackWidth.SetError(tbxWidthBackIamge, string.Empty);
}
请注意,我用string.Empty
代替了"(从不这样做).我还建议添加Trim
,假定仅包含空格字符的字符串也是无效的.如果我的假设是错误的,只需删除Trim
.
更好的是,使用匿名委托:
Pay attention, I use string.Empty
instead of "" (never do it). I also suggest to add Trim
assuming that a string containing only blank space characters is also invalid. If my assumption is wrong, simply remove Trim
.
Better yet, use anonymous delegate:
myControl.Validated += delegate(object sender, System.EventArgs eventArgs) {
if (tbxBackImage.Text.Trim() == string.Empty)
this.errBackWidth.SetError(tbxWidthBackIamge, "Enter the Width");
else
this.errBackWidth.SetError(tbxWidthBackIamge, string.Empty);
}
在C#v.3或v.4中,您可以使用lambda形式的委托使用更好的语法:
With C# v.3 or v.4 you could use the even better syntax with lambda form of the delegate:
myControl.Validated += (sender, eventArgs) => {
if (tbxBackImage.Text.Trim() == string.Empty)
this.errBackWidth.SetError(tbxWidthBackIamge, "Enter the Width");
else
this.errBackWidth.SetError(tbxWidthBackIamge, string.Empty);
}
请参阅此MSDN帮助页面上的代码示例: http://msdn.microsoft. com/en-us/library/system.windows.forms.errorprovider.aspx [ ^ ].
您的代码甚至可以编译吗?我的意思是,您要配置的errBackHeight
是什么.它实现IDisposable
吗?为什么要对错误进行任何处理?只是检查.
See the code sample on this MSDN help page: http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx[^].
Does your code even compile? I mean, what is errBackHeight
which you dispose. Does it implement IDisposable
? Why disposing anything on error? Just checking.
这篇关于错误提供程序中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!