views:

15

answers:

1

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?

+1  A: 

Page.FindControl is not recursive, it only searches what is directly in the control collection. It's coming up null because the control you're searching for is nested in the UserControl.

You can see a version of a recursive FindControl function here.

womp