Fire events manually

I have some controls on my form that I have assigned (via the constructor) functions to the Leave property, something like this:

textBox1.Leave += new System.EventHandler(f1);
textBox2.Leave += new System.EventHandler(f2);
textBox3.Leave += new System.EventHandler(f3);

      

These functions do some checking for text fields. Note that not all text boxes invoke the same delegate.

Now I need to tell them "hey, fire me when I want." In my case, I call this function somewhere in the beginning:

private void validateTextBoxes()
{
    foreach (Control c in c.Controls)
    {
        TextBox tb = c as TextBox;
        if (tb != null)
        {
            // Fire the tb.Leave event to check values
        }
    }
}

      

Thus, each text field checks its own code.

+3


source to share


2 answers


I'm assuming you really don't want to fire the Leave event, you just want to validate the textbox the same way it did, why not just fire them both with the same validation method.

private void ValidateTextBox(TextBox textBox)
{
    //Validate your textbox here..
}

private void TextBox_Leave(object sender,EventArgs e)
{
    var textbox = sender as TextBox;
    if (textbox !=null)
    {
        ValidateTextBox(textbox);
    } 
}

      

then connect the vacation event



textBox1.Leave += new System.EventHandler(TextBox_Leave);
textBox2.Leave += new System.EventHandler(TextBox_Leave);
textBox3.Leave += new System.EventHandler(TextBox_Leave);

      

then your original verification code.

private void validateTextBoxes()
{
    foreach (Control c in c.Controls)
    {
        TextBox tb = c as TextBox;
        if (tb != null)
        {
            // No need to fire leave event 
            //just call ValidateTextBox with our textbox
            ValidateTextBox(tb);
        }
    }
}

      

+5


source


As an alternative to your current approach, you may need to use Validating instead , which is exactly what this type of thing is for.

If you are using Validating you can use ContainerControl. ValidateChildren () to execute validation logic for all child controls. Note that the Form class implements ValidateChildren ().



Personally, I think what you should do.

+2


source







All Articles