ASP.NET의 div에 대한 코드 숨김 파일에서 CSS 스타일을 어떻게 수정합니까?


96

내 aspx 페이지의 코드에서 데이터베이스 테이블에서 얻은 정보를 기반으로 div의 CSS 스타일 특성을 수정하려고합니다. 다음은 본질적으로 내가하려는 일이지만 오류가 발생합니다.

Aspx :

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

비하인드 코드 :

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

내가 뭘 잘못하고 있죠?

답변:


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

6
testSpace.Attributes.Add ( "style", "display : none;"); 또한 작동합니다.
Robert C. Barth

2
Robert는 확실하지 않습니다. 두 스타일을 병합하는 대신 기존 스타일을 새 스타일로 대체 할 것이라고 생각합니다.
Necriis

1
유용하게는 기존 스타일을 대체합니다. 예를 들어 클래스 속성을 완전히 변경하고자 할 수 있습니다.
Andrew Morton

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 버전에만 해당됩니까?
Adam Miller

1
미안 해요. 첫 번째는 VB.net 접근 방식이었습니다. 난 내 대답 편집합니다
Nikolaj 잰더

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" }
    },
  }
};
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.