112

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?

4 Answers 4

173
testSpace.Style.Add("display", "none");
3
  • 7
    testSpace.Attributes.Add("style", "display: none;"); would also work. Commented Mar 18, 2009 at 6:38
  • 2
    No so sure Robert, I think this line will replace existing style with the new one instead of merging both styles.
    – Necriis
    Commented Jan 21, 2015 at 9:23
  • 1
    Usefully, this replaces an existing style, e.g. you might want to completely change a class attribute. Commented Feb 14, 2018 at 15:36
79

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";
0
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"
2
  • 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? Commented Mar 13, 2015 at 14:32
  • 1
    i am sorry. the first one was the VB.net approach. i will edit my answer Commented Mar 16, 2015 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" }
    },
  }
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.