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?