Change CSS classes from code

后端 未结 7 909
误落风尘
误落风尘 2020-12-03 06:17

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

7条回答
  •  一个人的身影
    2020-12-03 07:00

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

提交回复
热议问题