I have a textbox with a Css class called 'required'. When a user click a button, I'd like to add additional Css Class to the textbox called 'error' without removing the 'required' class. I want to accomplish this from code-behind.
I have a textbox with a Css class called 'required'. When a user click a button, I'd like to add additional Css Class to the textbox called 'error' without removing the 'required' class. I want to accomplish this from code-behind.
Here's a simple C# method to add or remove a CssClass into a WebControl...
public static void SetOrRemoveCssClass( WebControl control, string className, bool adding )
{
string[] splitClasses = control.CssClass.Split(' ');
bool hasNow = splitClasses.Contains( className );
if ( adding && !hasNow )
{
control.CssClass += " " + className;
}
else if ( !adding && hasNow ) // remove the CssClass attribute
{
control.CssClass = control.CssClass.Replace( className, "");
}
control.CssClass = control.CssClass.Replace(" "," ").Trim();
}