如何修改 ASP.NET 中 div 文件后面代码中的 CSS 样式?

我试图修改一个 div 的 CSS 样式属性,该属性基于我在 aspx 页面后面的代码中从数据库表中获得的信息。下面就是我正在尝试做的事情,但是我得到了错误。

Aspx:

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

暗号:

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

我做错了什么?

333420 次浏览
testSpace.Style.Add("display", "none");

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";

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"

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" }
},
}
};