Add additional Css class programmatically

Dragan picture Dragan · Jun 27, 2011 · Viewed 29k times · Source

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.

Answer

FSA picture FSA · Mar 7, 2013

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());
        }
    }
}