![](https://images.cnblogs.com/cnblogs_com/scsuns520/1002.jpg)
![](https://images.cnblogs.com/cnblogs_com/scsuns520/1003.jpg)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddpFavorite" runat="server" AutoPostBack="True"
onselectedindexchanged="ddpFavorite_SelectedIndexChanged">
<asp:ListItem Value="1">红色</asp:ListItem>
<asp:ListItem Value="2">绿色</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
新建样式表red.css
body
{
background-color:Red;
}
新建样式表blue.css
body
{
background-color:Blue;
}
打开Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
string Favorite
{
get
{
if (ViewState["Favorite"] != null)
{//判断视图状态是否为空
return ViewState["Favorite"].ToString();
}
else
{//默认为红色
ViewState["Favorite"] = "1";
}
return "1";
}
set
{
ViewState["Favorite"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//创建对象
HtmlGenericControl link = new HtmlGenericControl();
//Attributes集合
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
link.TagName = "link";
//判断用户选择值
if (Page.IsPostBack)
{//回传
string csspath = String.Empty;
switch (Favorite)
{
case "2":
csspath = "red.css";
break;
case "1":
csspath = "blue.css";
break;
}
link.Attributes.Add("href", csspath);
}
else if(!Page.IsPostBack)
{//不回传
string csspath = String.Empty;
switch(Favorite)
{
case "1":
csspath = "red.css";
break;
case "2":
csspath = "blue.css";
break;
}
link.Attributes.Add("href", csspath);
}
this.Controls.Add(link);
}
在Default.cs设计中双击DropDownList
protected void ddpFavorite_SelectedIndexChanged(object sender, EventArgs e)
{
//获取列表控件中选定的值
Favorite = this.ddpFavorite.SelectedValue;
}
}
按Ctrl+F5运行,Ok!简单的一个根据选择,背景风格css转换就完成了!