【问题标题】:How do you modify a CSS style in the code behind file for divs in ASP.NET?如何在 ASP.NET 中为 div 修改代码隐藏文件中的 CSS 样式?
【发布时间】:2010-10-14 00:24:02
【问题描述】:

我正在尝试根据我从我的 aspx 页面后面代码中的数据库表中获得的信息来修改 div 的 CSS 样式属性。以下基本上是我想要做的,但我得到了错误。

aspx:

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

代码背后:

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

我做错了什么?

【问题讨论】:

    标签: c# asp.net css


    【解决方案1】:

    如果你用initializer syntax newing 一个元素,你可以这样做:

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

    【讨论】:

      【解决方案2】:

      这是一个 HtmlGenericControl,所以不确定推荐的方法是什么,所以你也可以这样做:

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

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

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

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

      【讨论】:

        【解决方案3】:

        另一种方法:

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

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

        在 vb.net 中你可以这样做:

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

        【讨论】:

        • 我在 .NET 4.0 的标签控件上使用 testSpace.Style.Item("display") = "none"; 时遇到了麻烦。我收到错误'System.Web.UI.CssStyleCollection' does not contain a definition for 'Item' . . . 。这是否特定于特定的 .NET 版本?
        • 对不起。第一个是 VB.net 方法。我将编辑我的答案
        【解决方案4】:
        testSpace.Style.Add("display", "none");
        

        【讨论】:

        • testSpace.Attributes.Add("style", "display: none;");也可以。
        • 不太确定,罗伯特,我认为这一行将用新样式替换现有样式,而不是合并两种样式。
        • 有用的是,这会替换现有样式,例如你可能想完全改变一个类属性。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-13
        • 2011-05-16
        • 2015-08-10
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多