开发者

Apply CSS class to invalid controls on web form

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 stat开发者_开发百科ic 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?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜