Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire events manually

Tags:

c#

I have some controls on my form to which I assigned (via designer) functions to the Leave envent, something like this:

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

These functions perform some validation on the textboxes. Note that not all the textboxes call the same delegate.

What I need now is to be able to tell them "hey, fire the Leave event" when I want. On my case I call this function somewhere at start:

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
        }
    }
}

So every textbox validates with its own code.

like image 861
Pockets Avatar asked Dec 20 '25 09:12

Pockets


2 Answers

I presume you dont really want to fire the Leave event you just want to validate the textbox in the same way the leave event would, why not just run them both through 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 wire up the leave event

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

then your initial validation 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);
        }
    }
}
like image 181
Richard Friend Avatar answered Dec 22 '25 22:12

Richard Friend


As an alternative to your current approach, you might want to consider using the Validating event instead, which is precisely for this kind of thing.

If you use Validating, you can then use ContainerControl.ValidateChildren() to perform the validation logic for all the child controls. Note that the Form class implements ValidateChildren().

Personally, I think that's what you should be doing.

like image 23
Matthew Watson Avatar answered Dec 22 '25 22:12

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!