[英]Minimize coding for validation in C#
我正在尝试验证Winform应用程序中的一组文本框。
if(string.IsNullOrEmpty(txtCarbohydrate.Text){
//todo
}
但是在我的表单中有几个文本框需要验证是否为空,不仅在当前的获胜表单中,而且在其他表单中也是如此。 如何创建可以验证多个文本框并在整个应用程序中可重用的方法或类?
编辑:我写过这样的东西,有什么建议可以改善它吗?
class ValidateEmpty
{
bool res = false;
//List<object> txt = new List<object>();
List<string> st = new List<string>();
public List<string> St
{
get { return st; }
set { st = value; }
}
public ValidateEmpty(List<string> _str)
{
this.st = _str;
}
public bool checkEmpty()
{
bool res = false;
for (int i = 0; i < St.Count(); i++ )
{
if(string.IsNullOrEmpty(St[i]))
{
res= true;
}
}
return res;
}
}
}`
您可以将它们放在列表中,然后在列表中循环。
List<TextBox> TextBoxes=new List<TextBox>() {txtCarbohydrate, txtProtein, txtFat};
foreach(TextBox tb in TextBoxes)
{
if(String.IsNullOrEmpty(tb.Text)
{
//do something
}
}
根据您的编辑,您想返回一个布尔值(很难理解您的代码和您要完成的工作,您需要清楚简明!)以指示TextBox是否为空。 您可以按照以下方法创建执行此操作的方法...
public static bool IsThereAnEmptyTextBox(List<TextBox> textBoxes)
{
bool emptyfound=false;
foreach(TextBox tb in textboxes)
{
if(String.IsNullOrEmpty(tb.Text)
{
emptyfound=true;
}
}
return emptyfound;
}
如果将此函数放在Utility类或基类等中,则可以从任何类调用此函数。如果要将其与paqogomez的答案结合使用,可以从这样的形式中调用它...
bool emptyfound=MyUtilities.IsThereAnEmptyTextBox(myForm.Controls.OfType<TextBox>().ToList());
我认为这是解决问题的一种可怕方法,但是我试图证明您可以如何完成您所要求的工作。
要以单一形式获取所有文本框,请使用Controls.OfType<T>
var controls = myForm.Controls.OfType<TextBox>();
foreach(TextBox tb in controls)
{
//do validation
}
根据您要执行的验证类型,您也可以按照@RandRandom的建议进行操作,并将所需的属性放在文本框中。 这将迫使用户在提交文本之前放入文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.