Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS classes from code

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 = true; and I'd like to apply a style as a visual cue that the item cannot be altered...easy enough:

.CssClass += " ReadOnlyStyle";

But at times I will also need to change the same element to ReadOnly = false; which means that I will need to remove the CSS class that I set without removing any other styles that I might have assigned.

What's the best way to do this?

like image 824
nailitdown Avatar asked Jan 15 '09 07:01

nailitdown


1 Answers

I've taken AnthonyWJones original code and amended it so that it works no matter what scenario:

static class WebControlsExtensions
    {
        public static void AddCssClass(this WebControl control, string cssClass)
        {
            List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            classes.Add(cssClass);

            control.CssClass = classes.ToDelimitedString(" ");
        }

        public static void RemoveCssClass(this WebControl control, string cssClass)
        {
            List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            classes.Remove(cssClass);

            control.CssClass = classes.ToDelimitedString(" ");
        }
    }

    static class StringExtensions
    {
        public static string ToDelimitedString(this IEnumerable<string> list, string delimiter)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string item in list)
            {
                if (sb.Length > 0)
                    sb.Append(delimiter);

                sb.Append(item);
            }

            return sb.ToString();
        }
    }
like image 183
John_ Avatar answered Oct 16 '22 00:10

John_