I got inspiration from the Odeds post and created these two extension methods that you should develop:
public static void AddCssClass(this WebControl control, params string[] args) { List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); List<string> classesToAdd = args.Where(x => !classes.Contains(x)).ToList<string>(); classes.AddRange(classesToAdd); control.CssClass = String.Join(" ", classes); } public static void RemoveCssClass(this WebControl control, params string[] args) { List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>(); classes = classes.Where(x => !args.Contains(x)).ToList<string>(); control.CssClass = String.Join(" ", classes); }
Methods are simply used to add or remove CSS classes from WebControls (from where Button s, Label s, Panel , etc. everything inherits), for example myButton.AddCssClass("class1", "class2");
or myButton.RemoveCssClass("class2");
.
This can be very little overhead, but managing the CssClass property can also be a little difficult, as you are forced to handle the spaces on your own.
How many times have you not seen this, for example?
string myCssClass = "class1"; myButton.CssClass += " " + myCssClass;
Please feel free to improve the methods! :)
source share