2

When using asp.net, is it possible to modify css properties in the c# back end code in the same as Div tags? I cannot get it to work.

For example:

HTML

<div id="myDiv" runat="server" style="height:10px; color:black;" />

C#

myDiv.Style.Add("color", "white");

This works, however I am trying to do the same to a css class instead. So if I had: CSS

 .myDivStyle
    {
       height:10px;
       color:black;
    }

How can I access this and change the color in c#? The only effective way I was able to find was to have two css classes and replace the class with another one such as the answer to this: Replacing css class solution

I have tried:

myDivStyle.Style.Add("color","white");

I was wondering if it is possible to include the runat="server" property directly to the css class. Thanks in advance.

Community
  • 1
  • 1
Jaiesh_bhai
  • 1,778
  • 8
  • 26
  • 41

4 Answers4

3
myDiv.Attributes.CssStyle.Add("color", "white");

This is how I do by adding CSS for the same based on the condition.

Incredible
  • 3,495
  • 8
  • 49
  • 77
2

Apply the CSS class via attributes, like this:

myDiv.Attributes["class"] = "myDivStyle"; 
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
0

You can also use Attributes like myDiv.Attributes.Add("class", "myDivStyle"); This is will add new class to div

Andy
  • 332
  • 1
  • 13
0

For add a CSS class through code behind (In C#) :

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

OR

C#

divControl.Attributes["class"] = "myClass";

VB

divControl.Attributes("class") = "myClass"

You'll need to have a rule like this one on your css file

.myClass
{
   height:200px; 
   /*...more styles*/
}

Check This

Community
  • 1
  • 1
Ishan Jain
  • 8,063
  • 9
  • 48
  • 75