简体   繁体   中英

error collection in asp.net webforms

I am trying to change the css of a textbox based on an error on the page. Say to turn the background of the textbox red. I want to do this through the base page so that each codebehind that inherits this base page will perform this function. I am trying to do this in the OnLoad event

protected override void OnLoad(EventArgs e)
{
    //code here
    base.OnLoad(e);
}

How do I access the error collection in the base page something like this...

for each(var error in Page.Errors)
{
    TextBox textBox = error.textboxInError;
    textBox.Background - Color = "Red";
}

To be more specific I want to trigger on page validation errors.

If you're using web forms validators, you could do something like this:

// Get a collection of all validators to check, sort of like this
var allValidators = new[] { validator1, validator2, validator3 };

foreach (var validator in allValidators)
{
    validator.Validate();
    var ctrl = (WebControl)Page.FindControl(validator.ControlToValidate);
    ctrl.BackColor = validator.IsValid ? Colors.Red : Colors.White;
}

Update

Apparently, the Page object has a collection of validators. See Page.Validators . Here's some revised code using that:

foreach (var validator in Page.Validators)
{
    validator.Validate();
    var ctrl = (WebControl)Page.FindControl(validator.ControlToValidate);
    ctrl.BackColor = validator.IsValid ? Colors.Red : Colors.White;
}

Check This tutorial Out . It will help you create a Custom Error Page, and trap the error at either Application, Page or Web.Config level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM