Advertisement
Advertisement


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?

2019/06/05
1
96
6/5/2019 9:06:41 PM

Accepted Answer

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


Another way to do it:

testSpace.Style.Add("display", "none");

or

testSpace.Style["background-image"] = "url(images/foo.png)";

in vb.net you can do it this way:

testSpace.Style.Item("display") = "none"
2015/03/16

If you're newing up an element with initializer syntax, you can do something like this:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Attributes = { ["style"] = "min-width: 35px;" }
    },
  }
};

Or if using the CssStyleCollection specifically:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Style = { ["min-width"] = "35px" }
    },
  }
};
2020/07/23

Source: https://stackoverflow.com/questions/657144
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]