It\'s easy to set CssClass in the code-behind, but this runs the risk of overwriting existing classes.
I need to set certain elements to ReadOnly
In C# 3 you can add some extension methods.
static class WebControlsExtensions
{
public static void AddCssClass (this WebControl control, string cssClass)
{
control.CssClass += " " + cssClass;
}
public static void RemoveCssClass (this WebControl control, string cssClass)
{
control.CssClass = control.CssClass.replace(" " + cssClass, "");
}
}
Usage:-
ctl.AddCssClass("ReadOnly");
ctl.RemoveCssClass("ReadOnly");
Note the RemoveCssClass is designed to remove only those classes added by AddCssClass and has the limitation that where 2 additional class names is added the shortest name should not match exactly the start of the longest name. E.g., If you added "test" and "test2" you can't remove test without corrupting the CssClass. This could be improved with RegEx by I expect the above to be adequate for your needs.
Note if you don't have C#3 then remove the this keyword from the first parameter and use the static methods in the conventional manner.