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 decided to create extension methods for WebControl to have a generic solution. Here's my code:
public static class WebControlExtensions
{
public static void AddCssClass(this WebControl control, string cssClass)
{
if (string.IsNullOrEmpty(control.CssClass))
{
control.CssClass = cssClass;
}
else
{
string[] cssClasses = control.CssClass.Split(' ');
bool classExists = cssClasses.Any(@class => @class == cssClass);
if (!classExists)
{
control.CssClass += " " + cssClass;
}
}
}
public static void RemoveCssClass(this WebControl control, string cssClass)
{
if (!string.IsNullOrEmpty(control.CssClass))
{
string[] cssClasses = control.CssClass.Split(' ');
control.CssClass = string.Join(" ", cssClasses.Where(@class => @class != cssClass).ToArray());
}
}
}