三色交替的下拉列表框
2005-07-08 17:01:25 来源:WEB开发网如下图所示,显示三种颜色交替的下拉框。
实现方法:
1.使用System.Web.UI.HtmlControls控件,把它作为服务器控件运行。
2.在后台为这个select控件绑定数据。
3.再调用一个自己写的函数为它的没个项目指定颜色。
实现代码(主要实现部分):
前台(WebForm1.aspx):
<SELECT id="Select1" style="WIDTH: 300px" name="Select1" runat="server">
<OPTION selected></OPTION>
</SELECT>
后台(WebForm1.aspx.cs):
PRivate void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "data source=localhost;initial catalog=Northwind;passWord=;"
+"persist security info=True;user id=sa;workstation id=APJ062;packet size=4096";
string sqlstr = "select Top 10 CustomerID, CompanyName from Customers";
cnn.Open();
SqlDataAdapter ad = new SqlDataAdapter(sqlstr,cnn);
DataTable dt = new DataTable();
ad.Fill(dt);
Select1.DataSource = dt;
Select1.DataTextField = "CompanyName";
Select1.DataValueField = "CustomerID";
Select1.DataBind();
BindSelectColor(Select1);
}
}
//为select控件的项目添加样式
void BindSelectColor(HtmlSelect select)
{
int num = 0;
string styleString = "";
for(int i = 0 ; i < select.Items.Count; i ++ )
{
num = i % 3;
switch(num)
{
case 0:
{
styleString = "COLOR: #000099; BACKGROUND-COLOR: #F4FAFF";
break;
}
case 1:
{
styleString = "COLOR: #990000; BACKGROUND-COLOR: #FFFAFB";
break;
}
case 2:
{
styleString = "COLOR: #009900; BACKGROUND-COLOR: #F4FFFA";
break;
}
}
select.Items[i].Attributes.Add("style",styleString);
}
}
赞助商链接