如下圖所示,顯示三種顏色交替的下拉方塊。
實作方法:
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);
}
}