Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call an EventHandler from another Method

Tags:

c#

.net

How can I call the following method from another method on same code behind page?

protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)
    {
        bool is_valid = txtDeliveryLastName.Text != "";
        txtDeliveryLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
        args.IsValid = is_valid;
    }

I don't know how to handle the (object sender, ServerValidateEventArgs args) bit. I call CustomValidatorDelLN_ServerValidate(); What do I put inside the brackets?

like image 499
ComfortablyNumb Avatar asked Dec 17 '22 09:12

ComfortablyNumb


1 Answers

Since you're not directly referencing the sender, and you're not properly using the ServerValidateEventArgs, you can shortcut things a bit:

var args = new ServerValidateEventArgs(String.Empty, false);
CustomValidatorDelLN_ServerValidate(null, args);

I wouldn't do that though. I would suggest a refactor. Calling an Event Handler from other code really doesn't make sense. You could easily pull out the validation logic and put it in a separate method. You could then use that new method from both spots in your code:

// You can call this method from both places
protected bool ValidateLastName()
{
    bool isValid = !String.IsNullOrWhiteSpace(txtDeliveryLastName.Text);
    txtDeliveryLastName.BackColor = isValid ? Color.White : Color.LightPink;
    return isValid;
}

// This would be the modified Event Handler
protected void CustomValidatorDelLN_ServerValidate(object sender,
    ServerValidateEventArgs args)
{
    args.IsValid = ValidateLastName();
}
like image 60
Justin Niessner Avatar answered Jan 04 '23 07:01

Justin Niessner