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


96

我正在尝试根据从aspx页面后面的代码中从数据库表中获取的信息来修改div的CSS样式属性。以下本质上是我要尝试执行的操作,但出现错误。

Aspx:

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

背后的代码:

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

我究竟做错了什么?

Answers:


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

6
testSpace.Attributes.Add(“ style”,“ display:none;”); 也可以。
罗伯特·C·巴思

2
罗伯特(Robert)不确定,我认为这条线会用新的样式替换现有样式,而不是将两种样式合并。
Necriis

1
有用的是,它替换了现有样式,例如,您可能希望完全更改类属性。
安德鲁·莫顿

74

这是一个HtmlGenericControl,所以不确定执行此操作的推荐方法是什么,因此您也可以执行以下操作:

testSpace.Attributes.Add("style", "text-align: center;");

要么

testSpace.Attributes.Add("class", "centerIt");

要么

testSpace.Attributes["style"] = "text-align: center;";

要么

testSpace.Attributes["class"] = "centerIt";

15

另一种方法是:

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

要么

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

在vb.net中,您可以这样操作:

testSpace.Style.Item("display") = "none"

testSpace.Style.Item("display") = "none";在.NET 4.0中的标签控件上使用时遇到问题。我弄错了'System.Web.UI.CssStyleCollection' does not contain a definition for 'Item' . . . 。是特定于特定的.NET版本吗?
亚当·米勒

1
对不起。第一个是VB.net方法。我将编辑我的答案
Nikolaj Zander

0

如果要new使用初始化语法来创建元素,则可以执行以下操作:

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

或者,如果CssStyleCollection专门使用:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Style = { ["min-width"] = "35px" }
    },
  }
};
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.