我试图在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;
}
}
} `
答案 0 :(得分:3)
您可以将它们放在列表中,然后遍历列表。
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的答案结合使用,您可以从这样的表单中调用它... < / p>
bool emptyfound=MyUtilities.IsThereAnEmptyTextBox(myForm.Controls.OfType<TextBox>().ToList());
我认为这是一种可怕的方式,但我试图证明你可以做你所要求的。
答案 1 :(得分:3)
要抓取单个表单中的所有文本框,请使用Controls.OfType<T>
var controls = myForm.Controls.OfType<TextBox>();
foreach(TextBox tb in controls)
{
//do validation
}
根据您正在进行的验证类型,您也可以执行@RandRandom建议并将所需属性放在文本框中。这将强制用户在提交文本之前输入文本。