使用ASP.NET直接控制CSS样式

使用JavaScript控制CSS样式有点麻烦,还是觉得直接使用C#操作更方便快捷,本文通过两个Button控制TextBox1的高度和背景色,以展示通过C#控制CSS样式的方法。以下是操作的实例:
一、前端代码(TestEditStyle.aspx.)如下:

 1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestEditStyle.aspx.cs" Inherits="Test_TestEditStyle" %>
 2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3<html xmlns="http://www.w3.org/1999/xhtml">
 4<head runat="server">    
 5<title>无标题页</title>
 6</head>
 7<body>
 8     <form id="form1" runat="server">
 9     <div>
10         <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
11         <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
12         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
13     </div>
14     </form>
15</body>
16&lt;/html&gt;<code class="language-csharp hljs"></code>
二、后台代码(TestEditStyle.aspx.cs)如下:
 1using System;
 2using System.Collections;
 3using System.Configuration;
 4using System.Data;
 5using System.Linq;
 6using System.Web;
 7using System.Web.Security;
 8using System.Web.UI;
 9using System.Web.UI.HtmlControls;
10using System.Web.UI.WebControls;
11using System.Web.UI.WebControls.WebParts;
12using System.Xml.Linq;
13public partial class Test_TestEditStyle : System.Web.UI.Page
14{    
15protected void Page_Load(object sender, EventArgs e)    
16{   
17}    
18protected void Button1_Click(object sender, EventArgs e)
19{
20         TextBox1.Style["background-color"] = "blue"; //背景设为蓝色 
21         TextBox1.Style["height"] = "200px";     //高度设为200
22}    
23protected void Button2_Click(object sender, EventArgs e)
24{
25         TextBox1.Style["background-color"] = "red";  //背景设为红色 
26         TextBox1.Style["height"] = "100px";      //高度设为100    
27}
28}
<p>
  三、补充说明:<br /> 只要在标签里加上runat =&#8221;server&#8221;和ID=&#8221;MyTag&#8221;,就可在后台代码中直接通过设置MyTag.Style的值来控制样式。  例如:<br /> 在前端加入:
</p>
1&lt;div id="mydiv" runat="server"&gt;&lt;/div&gt;
<p>
  后台即可以直引用mydiv这个对像进行控制:
</p>
1mydiv.Style["width"] = "100px";
2mydiv.Style["height"] = "100px";
3mydiv.Style["background-color"] = "yellow";
<p>
  (以上代码在VS2008上调试通过)
</p>