joncodo
joncodo

Reputation: 2338

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.

Upvotes: 0

Views: 391

Answers (2)

Jacob
Jacob

Reputation: 78890

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

Upvotes: 2

Hanlet Escaño
Hanlet Escaño

Reputation: 17380

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.

Upvotes: 0

Related Questions