开发者

error collection in asp.net webforms

开发者 https://www.devze.com 2023-04-06 20:46 出处:网络
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 t

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.textboxInErro开发者_运维技巧r;
    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.

0

精彩评论

暂无评论...
验证码 换一张
取 消