110

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
EverTheLearner
  • 7,040
  • 16
  • 57
  • 72

4 Answers4

171
testSpace.Style.Add("display", "none");
Andy White
  • 86,444
  • 48
  • 176
  • 211
77

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";
TylerH
  • 20,799
  • 66
  • 75
  • 101
nickytonline
  • 6,855
  • 6
  • 42
  • 76
17

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"
Nikolaj Zander
  • 1,270
  • 9
  • 13
  • I had trouble using `testSpace.Style.Item("display") = "none";` on a label control in .NET 4.0. I got the error `'System.Web.UI.CssStyleCollection' does not contain a definition for 'Item' . . . `. Is that specific to a particular .NET version? – Adam Miller Mar 13 '15 at 14:32
  • 1
    i am sorry. the first one was the VB.net approach. i will edit my answer – Nikolaj Zander Mar 16 '15 at 14:26
0

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" }
    },
  }
};
Synctrex
  • 811
  • 1
  • 11
  • 19