SIGN UP MEMBER LOGIN:    
ARTICLE

Working with DropDownList and ListBox Controls in ASP.NET

Posted by Sushila Patel Articles | WebForms Controls July 29, 2003
In this article we'll see how to use DropDownList and ListBox Web controls to display data in various formats.
Reader Level:

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.

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[i].Attributes.Add("style", "color:" + ds.Tables[0].Rows[i]"CategoryColor"].ToString () );
}
}
}

VB.NET

Dim
myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myconnection =
New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;")
myda =
New SqlDataAdapter("Select * from CategoryTable ", myconnection)
ds =
New DataSet
myda.Fill(ds, "AllTables")
DropDownList1.DataSource = ds
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()
Dim i As Integer
For i = 0 To DropDownList1.Items.Count - 1
DropDownList1.Items(i).Attributes.Add("style", "color:" + ds.Tables(0).Rows(i)"CategoryColor").ToString())
Next
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:

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

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 Products ", mycn);
ds =
new DataSet();
myda.Fill (ds,"Table");
for(int i = 0 ;i < ds.Tables[0].Rows.Count - 1;i++)
{
listBox1.Items.Add (
new ListItem(ds.Tables[0].Rows[i]["UnitPrice"].ToString(),ds.Tables[0].Rows[i]["ProductID"].ToString()));
if(Convert.ToDouble(ds.Tables[0].Rows[i]["UnitPrice"].ToString()) <= 25 )
{
listBox1.Items[i].Attributes.Add("style", "color:red");
}
else
{
listBox1.Items[i].Attributes.Add("style", "color:green");
}
}
}
}

VB.NET

Dim
myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myconnection =
New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;")
myda =
New SqlDataAdapter("Select * from Products ", myconnection)
ds =
New DataSet
myda.Fill(ds, "AllTables")
Dim i As Integer
For i = 0 To ds.Tables(0).Rows.Count - 1
listBox1.Items.Add(
New ListItem(ds.Tables(0).Rows(i)("UnitPrice"), ds.Tables(0).Rows(i)("ProductID")))
If ds.Tables(0).Rows(i)("UnitPrice") <= 25 Then
listBox1.Items(i).Attributes.Add("style", "color:red")
Else
listBox1.Items(i).Attributes.Add("style", "color:green")
End If
Next
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

<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#
using System.Reflection;
VB.NET
Imports System.Reflection

C#
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
foreach(FieldInfo col in typeof(KnownColor).GetFields() )
{
if (col.FieldType == typeof(KnownColor) )
{
DropDownList1.Items.Add(
new ListItem(col.Name ,col.Name));
}
}
}
for (int i= 0 ;i < DropDownList1.Items.Count;i++)
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
}
}

VB.NET

Private
Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
Dim col As FieldInfo
For Each col In GetType(KnownColor).GetFields
If col.FieldType Is GetType(Drawing.KnownColor) Then
DropDownList1.Items.Add(New ListItem(col.Name, col.Name))
End If
Next
End If
Dim i As Integer
For i = 0 To DropDownList1.Items.Count - 1
DropDownList1.Items(i).Attributes.Add("style", "background-color:" + DropDownList1.Items(i).Text)
Next
End
Sub

Method 2:

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

C#
using System.ComponentModel;
VB.NET
Imports System.ComponentModel

C#
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())
{
ListItem li =
new ListItem();
li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c);
this.DropDownList1.Items.Add(li);
}
}
for (int i= 0 ;i < DropDownList1.Items.Count;i++)
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
}
}

VB.NET

Private
Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
Dim c As Color
For Each c In TypeDescriptor.GetConverter(GetType(Color)).GetStandardValues()
Dim
li As New ListItem
li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c)

Me
.DropDownList1.Items.Add(li)
Next c
End If
Dim i As Integer
For i = 0 To DropDownList1.Items.Count - 1
DropDownList1.Items(i).Attributes.Add("style", "background-color:" + DropDownList1.Items(i).Text)
Next
End
Sub

Login to add your contents and source code to this article
Article Extensions
Contents added by prince lucky on Nov 04, 2010
Thanks Great example.
share this article :
post comment
 

Hi, I am using a dropdown where I bind the items from the database.I have two items from the db for eg: Say I have "One" and "Two" as items in the dropdown, now I want to add an item dynamically from my C# program say "-select One-" and this item should be the default item in the dropdown on every page load. Please help me for the same.

Posted by Durga Feb 14, 2011

i have 2 radio button if i select one corresponding field with drop down list have to get enabled and wen i select the other....the other option have to get enabled...

example...

complaint     urgency (two radio button)
complaint  class    ( dropdownlist of classes)
urgency  (drop down list of urgency)

when i select the radio button  complaint the complaint class have to get enabled and when i select urgency the corresponding field have to get enabled



vidya

Posted by vidya m p May 09, 2010

i need to display all the details in textboxes like ename,sal,job,location etc by selecting eno using dropdownlist...

plsss help me

Posted by Anjaneya Prasad Dec 25, 2009

i want code of drop down list .. for ex. if select state than city list will be enabled ...

Posted by bhayyasaheb kamble May 08, 2009

One way to accomplish this is to filter the data coming from the database by including the Distinct clause in your SQL statement.  So the command might look like this

Select Distinct ProductID from Products

This would show only one occurence of a given ProductID even though there may be several.

Posted by Gary Irons Feb 03, 2009
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor