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'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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With