简体   繁体   English

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

[英]How do you modify a CSS style in the code behind file for divs in ASP.NET?

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.我正在尝试根据我从 aspx 页面后面代码中的数据库表中获得的信息来修改 div 的 CSS 样式属性。 The following is essentially what I am trying to do, but I get errors.以下基本上是我想要做的,但我得到了错误。

Aspx: ASP:

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

Code Behind:代码背后:

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

What am I doing wrong?我究竟做错了什么?

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:这是一个 HtmlGenericControl 所以不确定推荐的方法是什么,所以你也可以这样做:

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:在 vb.net 你可以这样做:

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

If you're new ing up an element with initializer syntax , you can do something like this:如果你用初始化语法new一个元素,你可以这样做:

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

Or if using the CssStyleCollection specifically:或者,如果专门使用CssStyleCollection

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM