Reputation: 458
Lets assume I have 5 TextBoxes like this:
textBox_Box1
textBox_Box2
textBox_Box3
textBox_Box4
textBox_Box5
And I have a function that checks if the TextBox contains only letters, like this:
public static bool OnlyLetters(string s)
{
foreach (char c in s)
{
if (!Char.IsLetter(c))
return false;
}
return true;
}
Is there an efficient way to check every textBox with this function? I do not want to write it in this style of course:
OnlyLetters(textBox_Box1.Text);
OnlyLetters(textBox_Box2.Text);
OnlyLetters(textBox_Box3.Text);
OnlyLetters(textBox_Box4.Text);
OnlyLetters(textBox_Box5.Text);
I would prefer to check it in a loop, but I do not know how to realize it at that point.
Upvotes: 0
Views: 101
Reputation: 589
You said you would like to check it in a 'Loop'. I don't know what GUI framework you are using so the types might be wrong, but you could do something like the following:
List<TextBox> textBoxes = new List<TextBox>();
// Add all your textBoxes to the list here
Then use a loop on the list of textBoxes whenever you want to check their contents. If it's a mobile platform you should probably see if it's possible to limit the type of keyboard shown, and on iOS you can automatically have the UI components added to the list so you don't have to manually write the code. Hope this helps a bit!
Upvotes: 0
Reputation: 14059
You could create an array of your TextBoxes:
private TextBox[] textBoxes = {
textBox_Box1,
textBox_Box2,
textBox_Box3,
textBox_Box4,
textBox_Box5
};
Then you can access it in a loop:
foreach (TextBox txt in textBoxes)
{
if (!OnlyLetters(txt.Text))
{
// Do something
}
}
Upvotes: 3
Reputation: 628
One way would be to put all your text boxes in some sort of container and then loop through the children of the container (which will be text boxes) and preform a check on each. That way, you can add and remove text boxes from the container as needed without modifying your code.
When you are looping through the text box container, check to see if the child you are on is in fact a text box, then preform a cast on it so you may access it's text property.
I do not know which framework you are using, so I cannot provide a code sample.
Upvotes: 0