简体   繁体   中英

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" 
runat="server"></asp:TextBox>
&nbsp; 
<asp:RequiredFieldValidator 
id="RequiredFieldValidator1" runat="server" 
ErrorMessage="Required!" 
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator>

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?

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.

A better option would be to inherit from the system validators and create your own validators. You can override the default behavior to change the background color of the ControlToValidate field. For most controls you don't need to check the type, you can just set the style value to "background-color:yellow".

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