Apply CSS class to invalid controls on web form

Posted by user137639 on Stack Overflow See other posts from Stack Overflow or by user137639
Published on 2010-06-17T21:19:14Z Indexed on 2010/06/17 21:23 UTC
Read the original article Hit count: 177

I need to apply a css class to invalid controls on a web form. I'd like to make it a resusable class. This is what I have so far:

public class Validation
{
    public static void ApplyInvalidClass(Page page, string className)
    {
        foreach (System.Web.UI.WebControls.BaseValidator bv in page.Validators)
        {
            if (!bv.IsValid)
            {
                Control ctrl = page.FindControl(bv.ControlToValidate);

                if (ctrl != null)
                {
                    if (ctrl is TextBox)
                    {
                        TextBox txt = ctrl as TextBox;
                        txt.CssClass = "invalid";
                    }

                    if (ctrl is DropDownList)
                    {
                        DropDownList ddl = ctrl as DropDownList;
                        ddl.CssClass = "invalid";
                    }

                    if (ctrl is CheckBox)
                    {
                        CheckBox cb = ctrl as CheckBox;
                        cb.CssClass = "invalid";
                    }

                    if (ctrl is HtmlGenericControl)
                    {
                        HtmlGenericControl html = ctrl as HtmlGenericControl;
                        html.Attributes.Add("class", className);
                    }
                }
            }
        }
    }

}

The problem is what I call this on a .Net user control, I guess because I'm passing in Page, page.FindControl(bv.ControlToValidate) is always null.

Is there a better way to do this?

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about webforms