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?
I made a version for pre-C#3:
Used like:
This one will only add a class if it's not already there. It will also remove all instances of a class (if, for some reason, there are multiple in there)
Pure .NET 2.0 (No extensions! No LINQ! No RegEx! No unnecessary WebControl class!). These methods are quite general to be used not for CSS classes only.
Can you make your own custom classes? Derive from the ASP.NET Button and add a propert for Read only. Somewhere...probably in the OnPreRender, you can check the new property and set (or not set) the CSSClass property accordingly.
Related... if you just want to toggle a Class based upon a condition...
In C# 3 you can add some extension methods.
Usage:-
Note the RemoveCssClass is designed to remove only those classes added by AddCssClass and has the limitation that where 2 additional class names is added the shortest name should not match exactly the start of the longest name. E.g., If you added "test" and "test2" you can't remove test without corrupting the CssClass. This could be improved with RegEx by I expect the above to be adequate for your needs.
Note if you don't have C#3 then remove the
this
keyword from the first parameter and use the static methods in the conventional manner.I've taken AnthonyWJones original code and amended it so that it works no matter what scenario: