106

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,816
  • 57
  • 73
  • 92
EverTheLearner
  • 6,740
  • 13
  • 54
  • 72

4 Answers4

166
testSpace.Style.Add("display", "none");
Andy White
  • 84,168
  • 47
  • 173
  • 207
74

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,816
  • 57
  • 73
  • 92
nickytonline
  • 6,805
  • 6
  • 41
  • 75
16

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,260
  • 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
  • 620
  • 9
  • 17