Chaos
Chaos

Reputation: 685

Attaching 1 validating event handler to Multiple textboxes

OverView

I have researched out there an I know there is a vast amount of info subscribing multiple event handlers to a single event however, I have not been able to apply it to my scenario. Pretty much I have a bout 30 of these validation event handlers from a textBox, all doing he same process. Below is one of those handlers:

  private void txt_HouseName_Validating(object sender, CancelEventArgs e)
        { // Convert User input to TitleCase After focus is lost.

            if (Utillity.IsAllLetters(txt_HouseName.Text) | !string.IsNullOrEmpty(txt_HouseName.Text))
            {
                errorProvider.Clear();
                txt_HouseName.Text = Utillity.ToTitle(txt_HouseName.Text);
                isValid = true;
            }
            else
            {
                errorProvider.SetError(txt_HouseName, "InValid Input, please  reType!!");
                isValid = false;

                //MessageBox.Show("Not Valid");
            }

        }

How would I minimizes my code to just one of these lines of code and only have one of these event handler? I know I should attach them within the designer code something similar to this

this.txt_Fax.Validating += new System.ComponentModel.CancelEventHandler(this.txt_Fax_Validating);

But as they are textboxes How would I go about attaching 1 validating events handlers to all of my TextBoxes

Upvotes: 0

Views: 451

Answers (1)

Suraj S
Suraj S

Reputation: 1019

You should be using the object sender parameter. as the sender is nothing but the object that called the Event Handler. So, have a global event handler and attach the same handler to all the text boxes. Your Event handler will look something like this.

private void txt_Validating(object sender, CancelEventArgs e)
        { // Convert User input to TitleCase After focus is lost.

          //Cast the sender to a textbox so we do not need to use the textbox name directly
            TextBox txtBx = (TextBox)sender; 
            if (Utillity.IsAllLetters(txtBx.Text) | !string.IsNullOrEmpty(txtBx.Text))
            {
                errorProvider.Clear();
                txtBx.Text = Utillity.ToTitle(txtBx.Text);//using the cast TextBox
                isValid = true;
            }
            else
            {
                errorProvider.SetError(txtBx, "InValid Input, please  reType!!");
                isValid = false;

                //MessageBox.Show("Not Valid");
            }

        }

Since the object sender parameter is passed with almost every event, it makes it easy to have a common callback for similar events and just check the sender and perform specific operations.

Upvotes: 3

Related Questions