Reputation: 276
I'm trying to validate a set of Textboxes in a winform application.
if(string.IsNullOrEmpty(txtCarbohydrate.Text){
//todo
}
but there are several Textboxes in my form to be validated for emptiness , not only in the current win form but other forms too. how can i create a method or a class that can validate several Textboxes and be reusable across application?
EDIT : i wrote somthing like this , any suggestion to make it better ?
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;
}
}
} `
Upvotes: 0
Views: 158
Reputation: 32694
You could put them in a list and then loop through the list.
List<TextBox> TextBoxes=new List<TextBox>() {txtCarbohydrate, txtProtein, txtFat};
foreach(TextBox tb in TextBoxes)
{
if(String.IsNullOrEmpty(tb.Text)
{
//do something
}
}
Based on your edit, you want to return a Boolean (it's really hard to understand your code and what you're trying to accomplish, you need to be clear and concise!) to indicate if a TextBox was empty or not. Here's how you could create a method to do that...
public static bool IsThereAnEmptyTextBox(List<TextBox> textBoxes)
{
bool emptyfound=false;
foreach(TextBox tb in textboxes)
{
if(String.IsNullOrEmpty(tb.Text)
{
emptyfound=true;
}
}
return emptyfound;
}
You can call this function from any class, if you put this function in a Utility class or in a base class etc. If you want to combine it with paqogomez's answer you can call it from a form like this...
bool emptyfound=MyUtilities.IsThereAnEmptyTextBox(myForm.Controls.OfType<TextBox>().ToList());
I think this is a terrible way of going about it, but I'm trying to demonstrate how you could do what you've asked for.
Upvotes: 3
Reputation: 15865
To grab all textboxes in a single form use Controls.OfType<T>
var controls = myForm.Controls.OfType<TextBox>();
foreach(TextBox tb in controls)
{
//do validation
}
Depending on the type of validation you are doing, you can also do as @RandRandom suggests and put the required attribute on your textboxes. This will force the user to put text in before its submitted.
Upvotes: 3