[c#] how to add css class to html generic control div?

I created a div tag like this:

System.Web.UI.HtmlControls.HtmlGenericControl dynDiv = 
    new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");

I added style to the div tag like this:

dynDiv.Style.Add(HtmlTextWriterStyle.BorderStyle, "1px solid #DBE0E4");
dynDiv.Style.Add(HtmlTextWriterStyle.Height, "auto");
dynDiv.Style.Add(HtmlTextWriterStyle.MarginTop, "5px");
dynDiv.Style.Add(HtmlTextWriterStyle.PaddingBottom, "5px");
dynDiv.Style.Add(HtmlTextWriterStyle.Width, "682px");

But I need to control the style of the div tag through an external css file located at folder ~/css/maincss.css.

How can I apply the css in that file to this div?

This question is related to c# css

The answer is


If you're going to be repeating this, might as well have an extension method:

// appends a string class to the html controls class attribute
public static void AddClass(this HtmlControl control, string newClass)
{
    if (control.Attributes["class"].IsNotNullAndNotEmpty())
    {
        control.Attributes["class"] += " " + newClass;
    }
    else
    {
        control.Attributes["class"] = newClass;
    }
}

To add a class to a div that is generated via the HtmlGenericControl way you can use:

div1.Attributes.Add("class", "classname"); 

If you are using the Panel option, it would be:

panel1.CssClass = "classname";

My approach would be:

/// <summary>
/// Appends CSS Class seprated by a space character
/// </summary>
/// <param name="control">Target control</param>
/// <param name="cssClass">CSS class name to append</param>
public static void AppendCss(HtmlGenericControl control, string cssClass)
{
    // Ensure CSS class is definied
    if (string.IsNullOrEmpty(cssClass)) return;

    // Append CSS class
    if (string.IsNullOrEmpty(control.Attributes["class"]))
    {
        // Set our CSS Class as only one
        control.Attributes["class"] = cssClass;
    }
    else
    {
        // Append new CSS class with space as seprator
        control.Attributes["class"] += (" " + cssClass);
    }
}

dynDiv.Attributes["class"] = "myCssClass";

How about an extension method?

Here I have a show or hide method. Using my CSS class hidden.

public static class HtmlControlExtensions
{
    public static void Hide(this HtmlControl ctrl)
    {
        if (!string.IsNullOrEmpty(ctrl.Attributes["class"]))
        {
            if (!ctrl.Attributes["class"].Contains("hidden"))
                ctrl.Attributes.Add("class", ctrl.Attributes["class"] + " hidden");
        }
        else
        {
            ctrl.Attributes.Add("class", "hidden");
        }
    }

    public static void Show(this HtmlControl ctrl)
    {
        if (!string.IsNullOrEmpty(ctrl.Attributes["class"]))
            if (ctrl.Attributes["class"].Contains("hidden"))
                ctrl.Attributes.Add("class", ctrl.Attributes["class"].Replace("hidden", ""));
    }
}

Then when you want to show or hide your control:

myUserControl.Hide();

//... some other code

myUserControl.Show();

if you want to add a class to an existing list of classes for an element:

element.Attributes.Add("class", element.Attributes["class"] + " " + sType);

You don't add the css file to the div, you add a class to it then put your import at the top of the HTML page like so:

<link href="../files/external.css" rel="stylesheet" type="text/css" />

Then add a class like the following to your code: 'myStyle'.

Then in the css file do something like:

.myStyle
{
   border-style: 1px solid #DBE0E4;
}

Alternative approach if you want to add a class to an existing list of classes of an element:

element.Attributes["class"] += " myCssClass";

I think the answer of Curt is correct, however, what if you want to add a class to a div that already has a class declared in the ASP.NET code.

Here is my solution for that, it is a generic method so you can call it directly as this:

Asp Net Div declaration:

<div id="divButtonWrapper" runat="server" class="text-center smallbutton fixPad">

Code to add class:

divButtonWrapper.AddClassToHtmlControl("nameOfYourCssClass")

Generic class:

public static class HtmlGenericControlExtensions
{
    public static void AddClassToHtmlControl(this HtmlGenericControl htmlGenericControl, string className)
    {
        if (string.IsNullOrWhiteSpace(className))
            return;

        htmlGenericControl
            .Attributes.Add("class", string.Join(" ", htmlGenericControl
            .Attributes["class"]
            .Split(' ')
            .Except(new[] { "", className })
            .Concat(new[] { className })
            .ToArray()));
    }
}