ASP.NET: How to change the background color of a control that failed validation


Let's take the following simple site as an example:

<asp:TextBox id="TextBox1" 
id="RequiredFieldValidator1" runat="server" 

Now, I would want the TextBox1 to change its BackColor to yellow when ever the validation has failed. Is there a simple way to accomplish this?

Best Solution

Page.Validators is a ValidatorCollection. You can iterate this collection casting each member to BaseValidator. Check BaseValidator.IsValid and get the name of the control from BaseValidator.ControlToValidate. Use this.FindControl(control name) to get a reference to the control (this returns a Control object). Perform whatever type checking and casting you need to do, and then if you can cast the control to TextBox or some other control that contains the BackColor property, cast it and set the BackColor.

Here's a simplified version:

   private void setInvalidControlsBackColor()
        Control c;
        TextBox t;
        foreach (BaseValidator v in Page.Validators)
            if (!v.IsValid)
                c = (Control)this.FindControl(v.ControlToValidate);
                // check the type, make sure you can cast this...
                t = (TextBox)c;
                t.BackColor = Color.Yellow;
                // or however else you want to handle this...

The reason I didn't include code for the type checking stuff is because you may want to handle the different control types differently, etc. Also, if you're not using the ToolTip fields on your validators, you can use this field to store additional info (kind of like the Tag property). That might be considered ugly practice, but it's there for you if you need it...can be used as a hint of what to do with valid/invalid states.

Related Question