Change CSS classes from code

后端 未结 7 847
误落风尘
误落风尘 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

    This version checks to make sure the given class isn't already added before adding it.

    public static void CssAddClass(this WebControl control, string className)
    {
        var classNames = control.CssClass.Split
            (new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    
        if (classNames.Contains(className))
        {
            return;
        }
    
        control.CssClass = string.Concat
            (classNames.Select(name => name + " ").ToArray()) + className;
    }
    
    public static void CssRemoveClass(this WebControl control, string className)
    {
        var classNames = from name in control.CssClass.
                             Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                         where name != className
                         select name + " ";
    
    
        control.CssClass = string.Concat(classNames.ToArray()).TrimEnd();
    }
    

提交回复
热议问题