Skip to content

Pass multiple components to single function

Jonathan

Asked Apr 1, 2009, 6:11 AM EDT1 answer
Share
LinkedInX
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?

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    I think I gave you the idea for a function earlier, you dont have to know what specific text box it is, just if its a text box or not.

    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.
    0