Pass multiple components to single function
I have no idea how to pass a large amount of objects to a single function. I have multiple textboxes that I need to compare. I want to write a generic function that checks to see if a textbox.text is between two values. I have to do this for 20 or so boxes. I can use the a textbox by name but how do I make a list of specific text boxes and then either pass them one by one in a loop?
Posted Apr 1, 2009, 4:50 PM
private bool IsTextInputValid(TextBox textBox)
{
int textBoxValue = 0;
if (Int32.TryParse(textBox.Text, out textBoxValue))
{
if (textBoxValue > 0 && textBoxValue < 10) // 0 and 10 are arbitrary numbers...
{
return true;
}
}
else
return false;
}
Alternatively you could attach a Validating event handler to each TextBox, but make the handler method the same for each text box.
// Assuming the event handler has already been attached to each text box.
private void textBox_Validating(object sender, CancelEventArgs e)
{
int textBoxValue = 0;
TextBox validatingBox = null;
if ((sender as TextBox) != null)
{
if (Int32.TryParse(textBox.Text, out textBoxValue))
{
if (textBoxValue < 0 || textBoxValue > 10) // 0 and 10 are arbitrary numbers...
{
// notify user some how, use an ErrorProvider control maybe?
}
}
else
{
// notify user some how, use an ErrorProvider control maybe?
}
}
}
This is the way I use most of the time. Its clean and I can handle multiple text boxes with it so long as I attach the handler to their Validating event.