views:

40

answers:

1

I'm trying to programatically add a second class to a <td> element in C#.

The element I want to add the class to already has a class assigned to it.

If I do something like

myObject.CssClass = "MyClass";

it simply overwrites the original class.

I suppose I could do something like

myObject.CssClass += " MyClass";

but that's ugly..

*disclaimer - I hate the idea of doing anything with HTML/CSS in C#, but I've been assigned to apply a quick fix to an already diabolical code-base. I don't see any point in trying to 'polish a turd' here, so please don't shoot me down!! :-)

+1  A: 

If you don't like to deal with string concatenation you could create some helper extension methods. Maybe more code, but you can add and remove classes without seeing what goes behind. And maybe the code will look clearer where you use it.

myObject.AddCssClass("someclass");
myObject.RemoveCssClass("someclass");

---------

public static class WebHelper
{
    public static void AddCssClass(this WebControl control, string cssClass)
    {
        List<string> classes;
        if (!string.IsNullOrWhiteSpace(control.CssClass))
        {
            classes = control.CssClass.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (!classes.Contains(cssClass))
                classes.Add(cssClass);
        }
        else
        {
            classes = new List<string> {cssClass};
        }
        control.CssClass = string.Join(" ", classes.ToArray());
    }

    public static void RemoveCssClass(this WebControl control, string cssClass)
    {
        List<string> classes = new List<string>();
        if (!string.IsNullOrWhiteSpace(control.CssClass))
        {
            classes = control.CssClass.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
        }
        classes.Remove(cssClass);
        control.CssClass = string.Join(" ", classes.ToArray());
    }
}
Mikael Svenson
Thanks Mikael. If there was an 'above and beyond the call of duty' badge, this answer would deserve it!
DaveDev
Sometimes it's better to show an alternative instead of saying "it is what it is" and the code was pretty straight forward :) Hope it helps.
Mikael Svenson