使用类的 ErrorProvider
我制作了以下课程,以避免重复 if else 代码,一次又一次:
public class Error
{
private ErrorProvider errProvider;
public void SetError(Control control, string value)
{
errProvider = new ErrorProvider();
if (control.Text.Trim().Length == 0)
{
errProvider.SetError(control, value);
}
else
{
errProvider.SetError(control, "");
}
}
}
文本框代码的验证是
private void textBox1_Validating(object sender, CancelEventArgs e)
{
erp.SetError(textBox1, "Please Enter Name");
}
- 在 texbox 中输入文本后,当我按 Enter 时,它工作正常;
- 无需在文本框中输入任何内容,当我按 Enter 时,它也会 工作正常表示出现Waring 红色图标;但
- 在警告之后,当我在文本框中输入文本后按 Tab 时, 警告图标不会消失,应该将其删除。
没有类,它可以在相同的代码更新下正常工作吗
?
I have made the following class to avoid the repetition if else code , again and again :
public class Error
{
private ErrorProvider errProvider;
public void SetError(Control control, string value)
{
errProvider = new ErrorProvider();
if (control.Text.Trim().Length == 0)
{
errProvider.SetError(control, value);
}
else
{
errProvider.SetError(control, "");
}
}
}
and validation on textbox code is
private void textBox1_Validating(object sender, CancelEventArgs e)
{
erp.SetError(textBox1, "Please Enter Name");
}
- After typing the text in texbox, as I press enter, it working fine;
- Without Entering any thing in textbox, as I press Enter , it also
working fine means Waring red icon appears; BUT - after warning, as I press tab after entering text in textbox ,
warning Icon does not disappear , it sould be removed.
without class it is working fine with the same code
update?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用Field Initializer
errProvider
应该使用Field Initializer,因为每次调用Error.SetError时,都会构造ErrorProvider,构造好的ErrorProvider不仅不会消失,还会继续存在。只是分层。[更新]
Use Field Initializer
You should use Field Initializer for
errProvider
, because every time calling Error.SetError, ErrorProvider will be constructed, and a constructed ErrorProvider will not only no disappear but also be just layered.[updated]
将 ErrorProvider 的构造移至声明行。因此,将: 更改
为:
并删除当前在 SetError 方法中的该成员的初始化。
向我们展示您如何以及何时创建和存储对您正在使用的 Error 类实例的引用也可能很有用。
另外,将验证代码放在名为 SetError 的方法中会有点误导(使代码更难维护)。我将其命名为 ValidateControlHasValue 或类似的名称。
Move the construction of your ErrorProvider to the declaration line. So change:
to:
and get rid of the initialization of that member that is currently in your SetError method.
It might also prove useful to show us how and when you are creating and storing a reference to the Error class instance you are using.
Also, putting your validation code inside of a method that is called SetError is a bit misleading (making your code harder to maintain). I'd name it something like ValidateControlHasValue or something like that.