How do you modify a CSS style in the code behind file for divs in ASP.NET?


Question

I'm trying to modify a CSS style attribute for a div based on the information I get from a database table in the code behind of my aspx page. The following is essentially what I am trying to do, but I get errors.

Aspx:

<div id="testSpace" runat="server">
    Test
</div>

Code Behind:

testSpace.Style = "display:none;"    
testSpace.Style("display") = "none";

What am I doing wrong?

1
91
6/5/2019 9:06:41 PM

Accepted Answer

testSpace.Style.Add("display", "none");
147
4/20/2012 4:09:12 AM

It's an HtmlGenericControl so not sure what the recommended way to do this is, so you could also do:

testSpace.Attributes.Add("style", "text-align: center;");

or

testSpace.Attributes.Add("class", "centerIt");

or

testSpace.Attributes["style"] = "text-align: center;";

or

testSpace.Attributes["class"] = "centerIt";

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon