ASP.NET Dropdown List Control: Eight Ways to Bind Data

This article shows you the real power of a dropdown list control available in ASP.NET. It also explains eight methods of binding data to the dropdown list.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 158
January 04, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable file for this article is available here.

The sample downloadable solution (zip) is entirely developed using Visual Studio.NET 2003 Enterprise Architect on Windows Server 2003 Standard Edition.  But, I am confident that it would work with other versions of Windows (which support .NET 1.1) as well.

What are the ways to bind data to a drop down list?

I don’t think there exists any meaningful application which does not have at least one “dropdownlist” control.  Every user definitely knows what a “dropdownlist” is.  The most important issue is that a “dropdownlist” can maintain two sets of values inside. 

The first set of values display generally the “textual” information (which is visible to the user).  The second set of values is “hidden” from the user.  The user would never know about the “hidden” information.  This flexibility is particularly necessary when you want to display only “student names” to the user and work with “regdno” behind the scenes.  Of course, the user may not identify any student just with the “regdno”!

Not every scenario needs the two sets of values.  Some may need only one set of values (both “text” and “value” would be the same).  The “dropdownlist” control in ASP.NET supports both of these scenarios. 

The process of attaching the “dropdownlist” control to a source of data is nothing but “data binding.”  This process of “binding” can occur in several ways including databases, arrays, and so on. In this article, we will mainly look at the following ways to bind (or place) information into a “dropdownlist” control.

  • Binding to a Simple Array
  • Binding to an ArrayList
  • Binding to a hashtable
  • Binding to a data table
  • Binding to a data set
  • Binding to a data view
  • Binding to a set of objects
  • Binding manually

The above are the most frequently used “data binding” mechanisms when we work with a “dropdownlist” in ASP.NET.  Now, let us go through each of those methodologies.

Binding to a Simple Array

This is the simplest of all.  It is generally used with only one set of values (rather than with two sets of values).  Let us go through the following code first:

Private Sub btnSimpleArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSimpleArray.Click

        Me.DropDownList1.Items.Clear()
        Dim months() As String = {"January", "February", "March", "April", "May", "June", "July"}
        Me.DropDownList1.DataSource = months
        Me.DropDownList1.DataBind()
    End Sub

The first statement clears all items in the “dropdownlist.”  The second statement creates a new array “months()” which can hold any number of strings (assigned during the declaration).  It is simultaneously filled with a set of month names.  “datasource” is a simple property of “dropdownlist” which can work with several types of “collections”. 

At this moment, we assigned a string array “month()” as the data source.  The last statement would make the “dropdownlist” fetch all the information from data source “month()” and fill itself.  That’s it. We are finished.

I also added two more routines, to check the “text” and “value” of a selected item in a particular “dropdownlist.”  Let us go through the two routines available.

Private Sub btnShowText_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowText.Click
        Me.lblText.Text = Me.DropDownList1.SelectedItem.Text
 
    End Sub

The above routine displays only the “text” (visible to the user) of the selected item within the “dropdownlist.”  Let us see the other:

     Private Sub btnShowValue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowValue.Click
        Me.lblValue.Text = Me.DropDownList1.SelectedItem.Value
    End Sub

The above routine displays only the “value” (which is hidden from the user) of the selected item within the “dropdownlist.”  In the case of “Binding a Simple Array,” there does not exist two sets of data.  It has only one set of data.  And thus both the “text” and “value” of the selected item of the “dropdownlist” would be same (which is “text” itself).

Binding to an ArrayList

Working with an “ArrayList” is also quite simple and straightforward.  Not only that, it has lot of flexibilities that a simple array does not have.  For example, we can remove, clear or do any manipulations within the “ArrayList” (which is a bit tedious to have in a simple array). 

Another beauty of an ArrayList is that it can contain any type of “object” (not just strings or integers).  We shall examine this feature later. 

Now, let us go through the following code:

Private Sub btnArrayList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnArrayList.Click
        Me.DropDownList1.Items.Clear()
        Dim ar As New ArrayList
        ar.Add("January")
        ar.Add("February")
        ar.Add("March")
        ar.Add("April")
        ar.Add("May")
        ar.Add("June")
        ar.Add("July")
        Me.DropDownList1.DataSource = ar
        Me.DropDownList1.DataBind()
    End Sub

I hope it is quite straightforward.  You declared a new “ArrayList” and started adding elements to it using the predefined method “add.”   But, make sure that even the “ArrayList” can contain only one set of items (and not two sets of items at the moment).

So, even now, the “text” and “value” of any selected item within the “dropdownlist” would still be the same.  

Binding to a Hashtable

Coming to the concept of “Hashtable”, it is very similar to an “ArrayList.”  But, it stores a “pair” of information (something like a key and a value).  This gives us the opportunity to have two sets of data!

Let us go through the following code.

Private Sub btnHastable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHastable.Click

        Me.DropDownList1.Items.Clear()
 
        Dim ht As New Hashtable
        ht.Add("1001", "jag1")
        ht.Add("1002", "jag2")
 
        Me.DropDownList1.DataSource = ht
        Me.DropDownList1.DataTextField = "value"
        Me.DropDownList1.DataValueField = "key"
        Me.DropDownList1.DataBind()
    End Sub

Let me explain part by part.  Let us first consider the following statements:

        Dim ht As New Hashtable
        ht.Add("1001", "jag1")

I am creating a new “hashtable” and adding “items” to it.  Each “item” needs to have a “key” and a “value.”  From the above statement, I am adding a single student (item) with his regdno (key) and name (value).  So, you now understand the concept of two sets of data. 

Further proceeding, we have:

Me.DropDownList1.DataSource = ht
        Me.DropDownList1.DataTextField = "value"
        Me.DropDownList1.DataValueField = "key"
        Me.DropDownList1.DataBind()
 
You can understand that the “text” (visible to the user) would be “value” (nothing but “name”) and “value” (hidden from the user) would be “key” (nothing but “regdno”).  That’s it.

Binding to data table, data set and data view

At the moment, for this article, I am trying to fetch the information from the database and then fill either the data table or data set.  Actually, you can even create your own “offline” table structure and add rows to a “data table” (or even a “data set”).  I leave that concept to the programmers to investigate those techniques, because it is beyond the scope of this article.

Now, let us connect to the database, fetch the information into the data table (or data set) and then bind it to the “dropdownlist.”

Private Sub btnDataTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataTable.Click
        Me.DropDownList1.Items.Clear()
        Dim da As New SqlDataAdapter("select productID,ProductName from Products", "data source=.;initial catalog=northwind;user id=sa")
        Dim dt As New DataTable
        da.Fill(dt)
        da.Dispose()
        Me.DropDownList1.DataSource = dt
        Me.DropDownList1.DataTextField = "ProductName"
        Me.DropDownList1.DataValueField = "ProductID"
        Me.DropDownList1.DataBind()
    End Sub
 
    Private Sub btnDataSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDataSet.Click
        Me.DropDownList1.Items.Clear()
        Dim da As New SqlDataAdapter("select productID,ProductName from Products", "data source=.;initial catalog=northwind;user id=sa")
        Dim ds As New DataSet
        da.Fill(ds, "Products")
        da.Dispose()
        Me.DropDownList1.DataSource = ds.Tables("Products")
        Me.DropDownList1.DataTextField = "ProductName"
        Me.DropDownList1.DataValueField = "ProductID"
        Me.DropDownList1.DataBind()
    End Sub

I think the above two methods should be quite familiar to every programmer.  Working with “data view” would also be very similar to that of “data table” or “data set,” except that we can “sort” or “filter” the data.  Let us look into that.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Me.DropDownList1.Items.Clear()
        Dim da As New SqlDataAdapter("select productID,ProductName from Products", "data source=.;initial catalog=northwind;user id=sa")
        Dim ds As New DataSet
        da.Fill(ds, "Products")
        da.Dispose()
        Dim dv As DataView = ds.Tables("Products").DefaultView
        dv.Sort = "ProductName desc"
        Me.DropDownList1.DataSource = dv
        Me.DropDownList1.DataTextField = "ProductName"
        Me.DropDownList1.DataValueField = "ProductID"
        Me.DropDownList1.DataBind()
    End Sub

Binding to a set of objects

If you have your own structure (defined in the form of “class” or “structure”), you can still use them to create several objects and together bind to the “dropdownlist.”

At this moment, I just created a simple class (CStudent) which can hold a “regdno” and “sname”.  I also defined two read/write properties to “set-get” the property values.  Let us go through the class first.

Public Class CStudent
    Private m_regdno As String
    Private m_sname As String
 
    Public Sub New(ByVal r As String, ByVal n As String)
        regdno = r
        sname = n
    End Sub
    Public Property regdno() As String
        Get
            Return m_regdno
        End Get
        Set(ByVal Value As String)
            m_regdno = Value
        End Set
    End Property
 
    Public Property sname() As String
        Get
            Return m_sname
        End Get
        Set(ByVal Value As String)
            m_sname = Value
        End Set
    End Property
End Class

Once you create the above class, we need to declare objects (along with values) to work with those classes.  Make sure that a “class” is simply a specification (or user-defined data type).  It does not allocate any memory to hold the values (unless you create the objects).  The following code creates a few objects based on the class “CStudent” and binds it to the “dropdownlist.”

Private Sub btnObjects_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnObjects.Click
        Me.DropDownList1.Items.Clear()
 
        Dim items As New ArrayList
        items.Add(New CStudent("1001", "jag1"))
        items.Add(New CStudent("1002", "jag2"))
        items.Add(New CStudent("1003", "jag3"))
 
        Me.DropDownList1.DataSource = items
        Me.DropDownList1.DataTextField = "sname"
        Me.DropDownList1.DataValueField = "regdno"
        Me.DropDownList1.DataBind()
 
    End Sub

As I mentioned earlier, the “ArrayList” can hold any type of object.  And now, you can see how helpful it is!

Binding Manually

Most programmers should already know about this concept.  We can manually add different types of items to the “dropdownlist.”

Let us go through the following:

Private Sub btnManual_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnManual.Click
        Me.DropDownList1.Items.Clear()
 
        Dim li As ListItem
        li = New ListItem
        li.Text = "first"
        li.Value = 1
        Me.DropDownList1.Items.Add(li)
 
        li = New ListItem("second")
        Me.DropDownList1.Items.Add(li)
 
        li = New ListItem("third", "3")
        Me.DropDownList1.Items.Add(li)
 
        For i As Integer = 4 To 10
            Me.DropDownList1.Items.Add(New ListItem("item" & i, i))
        Next
 
    End Sub

Even within the above program, I tried to give you several ways of adding “one set” or “two sets” of information manually to a “dropdownlist.”

Any comments, suggestions, bugs, errors, feedback etc. are highly appreciated at jag_chat@yahoo.com

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials