Working with DropDownList and ListBox Controls in ASP.NET

Introduction

This article is based on queries in the newsgroup:

Query 1 :"In my application i am using dropdownlist to display all categories from a table. When the user clicks this control I display all records in that category. Category table also contains column called color.

I wanted display some categories in dropdown list different color and others in different color using ASP.NET."-Anonymous

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.

So as stated by the MS Article the alternative method to achieve this is by using the tag given below:

  1. <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#

  1. SqlConnection mycn;  
  2. SqlDataAdapter myda;  
  3. DataSet ds;  
  4. String strConn;  
  5. private void Page_Load(object sender, System.EventArgs e)  
  6. {  
  7.     if (!IsPostBack)  
  8.     {  
  9.         strConn = "Data Source=localhost;uid=sa;pwd=;Initial Catalog=northwind";  
  10.         mycn = new SqlConnection(strConn);  
  11.         myda = new SqlDataAdapter("Select * FROM CategoryTable ", mycn);  
  12.         ds = new DataSet();  
  13.         myda.Fill(ds, "Table");  
  14.         DropDownList1.DataSource = ds.Tables[0];  
  15.         DropDownList1.DataTextField = ds.Tables[0].Columns["CategoryName"].ColumnName.ToString();  
  16.         DropDownList1.DataValueField = ds.Tables[0].Columns["CategoryId"].ColumnName.ToString();  
  17.         DropDownList1.DataBind();  
  18.         for (int i = 0; i < DropDownList1.Items.Count; i++)  
  19.         {  
  20.             DropDownList1.Items[i].Attributes.Add("style""color:" + ds.Tables[0].Rows[i]"CategoryColor"].ToString() );  
  21.     }  
  22. }  
VB.NET
  1. Dim myconnection As SqlConnection  
  2. Dim myda As SqlDataAdapter  
  3. Dim ds As DataSet  
  4. Private Sub Page_Load(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles MyBase.Load  
  5. myconnection =New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;")  
  6. myda =New SqlDataAdapter("Select * from CategoryTable ", myconnection)  
  7. ds =New DataSet  
  8. myda.Fill(ds, "AllTables")  
  9. DropDownList1.DataSource = ds  
  10. DropDownList1.DataSource = ds.Tables(0)  
  11. DropDownList1.DataTextField = ds.Tables(0).Columns("CategoryName").ColumnName.ToString()  
  12. DropDownList1.DataValueField = ds.Tables(0).Columns("CategoryId").ColumnName.ToString()  
  13. DropDownList1.DataBind()  
  14. Dim i As Integer  
  15. For i = 0 To DropDownList1.Items.Count - 1  
  16. DropDownList1.Items(i).Attributes.Add("style""color:" + ds.Tables(0).Rows(i)"CategoryColor").ToString())  
  17. Next  
  18. End Sub
Query 2 :"Is it possible for a listbox to show Products having Price above a specific value in one color and the ones below that value in different color"-Anonymous

To solve this the concept remains same only thing we need to do is use the ListBox and navigate through each and every record in dataset to have item with appropriate color. So lets consider the Products Table in Northwind Database and expect the output as below:

  
 
Tag that we use:

  1. <SELECT id="listBox1" size="10" runat="server" NAME="listBox1"></SELECT>  
Coding Step:
  • Populate the dataset
  • Navigate through the Rows checking for the value in the DataBase and the specific value (in our case its set to 25)
  • Depending on the value assign the style property for each item in the ListBox

Code given below:

C#

  1. SqlConnection mycn;  
  2. SqlDataAdapter myda;  
  3. DataSet ds;  
  4. String strConn;  
  5. private void Page_Load(object sender, System.EventArgs e)  
  6. {  
  7.     if (!IsPostBack)  
  8.     {  
  9.         strConn = "Data Source=localhost;uid=sa;pwd=;Initial Catalog=northwind";  
  10.         mycn = new SqlConnection(strConn);  
  11.         myda = new SqlDataAdapter("Select * FROM Products ", mycn);  
  12.         ds = new DataSet();  
  13.         myda.Fill(ds, "Table");  
  14.         for (int i = 0; i < ds.Tables[0].Rows.Count - 1; i++)  
  15.         {  
  16.             listBox1.Items.Add(new ListItem(ds.Tables[0].Rows[i]["UnitPrice"].ToString(), ds.Tables[0].Rows[i]["ProductID"].ToString()));  
  17.             if (Convert.ToDouble(ds.Tables[0].Rows[i]["UnitPrice"].ToString()) <= 25)  
  18.             {  
  19.                 listBox1.Items[i].Attributes.Add("style""color:red");  
  20.             }  
  21.             else  
  22.             {  
  23.                 listBox1.Items[i].Attributes.Add("style""color:green");  
  24.             }  
  25.         }  
  26.     }  
  27. }
VB.NET
  1. Dim myconnection As SqlConnection  
  2. Dim myda As SqlDataAdapter  
  3. Dim ds As DataSet  
  4. Private Sub Page_Load(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles MyBase.Load  
  5. myconnection =New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;")  
  6. myda =New SqlDataAdapter("Select * from Products ", myconnection)  
  7. ds =New DataSet  
  8. myda.Fill(ds, "AllTables")  
  9. Dim i As Integer  
  10. For i = 0 To ds.Tables(0).Rows.Count - 1  
  11. listBox1.Items.Add(New ListItem(ds.Tables(0).Rows(i)("UnitPrice"), ds.Tables(0).Rows(i)("ProductID")))  
  12. If ds.Tables(0).Rows(i)("UnitPrice") <= 25 Then  
  13. listBox1.Items(i).Attributes.Add("style""color:red")  
  14. Else  
  15. listBox1.Items(i).Attributes.Add("style""color:green")  
  16. End If  
  17. Next  
  18. End Sub  
Sample Code

As we have done the coding for assigning style property to each item we might as well complete the code to develop a Color Picker in ASP.NET as below:

So the control we use is

  1. <SELECT id="DropDownList1" name="DropDownList1" runat="server"></SELECT>  

And code for this is as below:

Method 1

We'll use the namespace System.Reflection to get the FieldInfo (i.e. Colors)

C#

  1. using System.Reflection;  
VB.NET
  1. Imports System.Reflection 

C#

  1. private void Page_Load(object sender, System.EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         foreach (FieldInfo col in typeof(KnownColor).GetFields())  
  6.         {  
  7.             if (col.FieldType == typeof(KnownColor))  
  8.             {  
  9.                 DropDownList1.Items.Add(new ListItem(col.Name, col.Name));  
  10.             }  
  11.         }  
  12.     }  
  13.     for (int i = 0; i < DropDownList1.Items.Count; i++)  
  14.     {  
  15.         DropDownList1.Items[i].Attributes.Add("style""background-color:" + DropDownList1.Items[i].Text);  
  16.     }  
  17. }
VB.NET
  1. Private Sub Page_Load(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles MyBase.Load  
  2. If Not Page.IsPostBack Then  
  3. Dim col As FieldInfo  
  4. For Each col In GetType(KnownColor).GetFields  
  5. If col.FieldType Is GetType(Drawing.KnownColor) Then  
  6. DropDownList1.Items.Add(New ListItem(col.Name, col.Name))  
  7. End If  
  8. Next  
  9. End If  
  10. Dim i As Integer  
  11. For i = 0 To DropDownList1.Items.Count - 1  
  12. DropDownList1.Items(i).Attributes.Add("style""background-color:" + DropDownList1.Items(i).Text)  
  13. Next  
  14. End Sub  

Method 2

The other way this can be done is by using Namespace System.ComponentModel and TypeDescripter Class.

C#

  1. using System.ComponentModel;
VB.NET
  1. Imports System.ComponentModel
C#
  1. private void Page_Load(object sender, System.EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         foreach (Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())  
  6.         {  
  7.             ListItem li = new ListItem();  
  8.             li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c);  
  9.             this.DropDownList1.Items.Add(li);  
  10.         }  
  11.     }  
  12.     for (int i = 0; i < DropDownList1.Items.Count; i++)  
  13.     {  
  14.         DropDownList1.Items[i].Attributes.Add("style""background-color:" + DropDownList1.Items[i].Text);  
  15.     }  
  16. }  
VB.NET
  1. Private Sub Page_Load(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles MyBase.Load  
  2. If Not Page.IsPostBack Then  
  3. Dim c As Color  
  4. For Each c In TypeDescriptor.GetConverter(GetType(Color)).GetStandardValues()  
  5. Dim li As New ListItem  
  6. li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c)  
  7. Me.DropDownList1.Items.Add(li)  
  8. Next c  
  9. End If  
  10. Dim i As Integer  
  11. For i = 0 To DropDownList1.Items.Count - 1  
  12. DropDownList1.Items(i).Attributes.Add("style""background-color:" + DropDownList1.Items(i).Text)  
  13. Next  
  14. End Sub 


Similar Articles