如下圖所示,顯示三種顏色交替的下拉框。
實現方法:
1.使用System.Web.UI.HtmlControls控件,把它作為服務器控件運行。
2.在後台為這個select控件綁定數據。
3.再調用一個自己寫的函數為它的沒個項目指定顏色。
實現代碼(主要實現部分):
前台(WebForm1.ASPx):
<SELECT id="Select1" 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);
}
}