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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With