As shown in the figure below, a drop-down box with three alternating colors is displayed.
Implementation method:
1. Use the System.Web.UI.HtmlControls control and run it as a server control.
2. Bind data to this select control in the background.
3. Then call a function you wrote to specify the color for each of its items.
Implementation code (main implementation part):
Front desk (WebForm1.aspx):
<SELECT id="Select1" style="WIDTH: 300px" name="Select1" runat="server">
<OPTION selected></OPTION>
</SELECT>
Backend (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);
}
}
//Add styles to the items of the select control
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);
}
}