Working with DropDownList and ListBox Controls in ASP.NET
Friday, March 30, 2007 9:25:17 AM


Note: The dropDownList has a bug which prevent us from assigning the style property to each item in the DropDownList.
So data in the database along with the desired output is as given below


Note: The dropDownList has a bug which prevent us from assigning the style property to each item in the DropDownList.
This bug confirmed by Microsoft in Microsoft Knowledge Base Article - 309338
So as stated by the MS Article the alternative method to achieve this is by using the tag given below:
<SELECT id="DropDownList1" name="DropDownList1" runat="server"></SELECT>
Now our code.As far as coding the steps we would follow are as below:
Fill the DataSet
Populate the DropDownList with the DataSet
Navigate through the DropDownList to give appropriate color to each item in the dropdown.
C#
SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
strConn="Data Source=localhost;uid=sa;pwd=;Initial Catalog=northwind";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter ("Select * FROM CategoryTable ", mycn);
ds = new DataSet();
myda.Fill (ds,"Table");
DropDownList1.DataSource =ds.Tables [0] ;
DropDownList1.DataTextField =ds.Tables[0].Columns["CategoryName"].ColumnName.ToString();
DropDownList1.DataValueField =ds.Tables[0].Columns["CategoryId"].ColumnName.ToString();
DropDownList1.DataBind () ;
for (int i =0;i < DropDownList1.Items.Count ;i++ )
{
DropDownList1.Items.Attributes.Add("style", "color:" + ds.Tables[0].Rows"CategoryColor"].ToString () );
}
}
}






