[c#] Add CSS class to a div in code behind

I have a div and I am trying to add a CSS class to it in code but I receive the following error when I try

Property or indexer 'System.Web.UI.HtmlControls.HtmlControl.Style' cannot be assigned to -- it is read only

I am using the following code:

protected void BTNEvent_Click(object sender, ImageClickEventArgs e)
{
    BtnventCss.Style= "hom_but_a";                 
}

Can anyone please help me?

This question is related to c# css

The answer is


For a non ASP.NET control, i.e. HTML controls like div, table, td, tr, etc. you need to first make them a server control, assign an ID, and then assign a property from server code:

ASPX page

<head>
    <style type="text/css">
        .top_rounded
        {
            height: 75px;
            width: 75px;
            border: 2px solid;
            border-radius: 5px;
            -moz-border-radius: 5px; /* Firefox 3.6 and earlier */
            border-color: #9c1c1f;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div runat="server" id="myDiv">This is my div</div>
    </form>
</body>

CS page

myDiv.Attributes.Add("class", "top_rounded");

Button1.CssClass += " newClass";

This will not erase your original classes for that control. Try this, it should work.


I'm also looking for the same solution. And I think of

BtnventCss.CssClass = BtnventCss.CssClass + " hom_but_a";

It seems working fine but I'm not sure if it is a good practice


To ADD classes to html elements see how to add css class to html generic control div?. There are answers similar to those given here but showing how to add classes to html elements.


The Style property gets a collection of all the cascading style sheet (CSS) properties; you cannot set it.

Try BtnventCss.CssClass = "hom_but_a"; instead.

I'm assuming BtnventCss is a WebControl.

I have just seen you're probably using <div runat="server"...

If so, you can try:

BtnventCss.Attributes.Add("class", "hom_but_a");

You could make the div an asp:panel - they will render the same and you'll get better server-side support.


Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.

public static void RemoveCssClass(this WebControl control, String css) {
  control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}

public static void AddCssClass(this WebControl control, String css) {
  control.RemoveCssClass(css);
  css += " " + control.CssClass;
  control.CssClass = css;
}

Usage: hlCreateNew.AddCssClass("disabled");

Usage: hlCreateNew.RemoveCssClass("disabled");


<div runat="server"> is mapped to a HtmlGenericControl. Try using BtnventCss.Attributes.Add("class", "hom_but_a");