Problem solve Get help with specific problems with your technologies, process and projects.

The low down on the DropDownList control

Overview of the control, how to use it and how to get data into it.

This tip was submitted to the Visual Studio .NET Info Center Tip Exchange by member Roger McCook. Let other users know how useful it is by rating the tip below. Got a tip or code of your own you'd like to share? Submit it here.


Whenever I see a DropDownList control, my brain says "Yes! That is a ComboBox!" That's because I've been programming in Visual Basic 6.0 for too long. VB6 has something called a ComboBox. It was given that name because it could be used in different ways. That was way cool, but whenever I had to write a help file or explain an application to a customer, I couldn't use the term "ComboBox" without them wrinkling their brow and frowning at me. The "combo" aspect of the control never made sense to users, only programmers. So I started calling it a drop-down list. That made more sense to the customer. No more wrinkled brows. No more frowns. (But sometimes in the middle of the night I would quietly whisper..."ComboBox! ComboBox!")

My brain is, however, quite wrong in identifying the DropDownList control as a ComboBox. It is not a ComboBox. NOT. It is just a single-line picklist control. Need a picklist? This is your control.

Properties, Methods and Events
 

Property Name Description
AutoPostBack Boolean. Automatically posts the form if True. Default is False.
DataMember Identifies the table in a data source to bind to the control.
DataSource Identifies the data source for the items in the list.
DataTextField Identifies the field in the data source to use for the option text.
DataValueField Indicates the field in the data source to use for the option values.
DataTextFormatString Format string for determining how the DataTextField is displayed.
Items Collection of items in the control.
SelectedIndex Indicates the index number of the selected option.
SelectedItem The selected item (duuh).
Method Name Description
DataBind Binds the control to its data source. This means the items from the data source are loaded into the controls ListItem collection.
OnSelectedIndexChanged Raises the SelectedIndexChanged event.
Event Name Description
SelectedIndexChanged The event is raised whenever a new option is selected.

How to get options into the DropDownList control 

1. If you are using Visual Studio, drag the DropDownList control from the toolbox onto the web form. Make sure you choose the control from the WebForms tab and not the HTML tab. After positioning the control where you want, resizing it and so on, you can manually enter the items into the list using Visual Studio. Go to the properties dialog for the control. If the properties dialog is not visible, right click on the control and select PROPERTIES from the menu. Find the entry for "Items" and click on the ellipsis button to bring up the ListItem Collection Editor. Click the ADD button on the left side of the editor. On the right side, enter "Georgia" in the text field and "GA" in the value field. Now click ADD again and enter "Florida" in the text field and "FL" in the value field. Click ADD again and enter "Alabama" in the text field and "AL" in the value field. Click the OK button. Now you have a DropDownList control with three list items. The text portion of each item will display the state name. The corresponding value will be the abbreviation of the selected state. 


2. You can access the text and value properties of the selected item in code as follows: 

    Dim strVariable as String 
    strVariable = DropDownList1.SelectedItem.Text      - To access the text portion  
    strVariable = DropDownList1.SelectedItem.Value    - To access the value portion 


3. If you are not using Visual Studio or if you just allergic to drag 'n drop, you can code the above directly following the following syntax: 

    <asp:DropDownList id="DropDownList1" runat="server">
        <asp:ListItem Value="GA">Georgia</asp:ListItem>
        <asp:ListItem Value="FL">Florida</asp:ListItem>
        <asp:ListItem Value="AL">Alabama</asp:ListItem>
     </asp:DropDownList>


4. You can write code to add your items also. Here is an example of how you might populate the control when the page loads for the first time. Notice, however, that we are only filling in the text portion of each option, not the value portion.  

    If Not Page.IsPostBack Then
        DropDownList1.Items.Add("Georgia")
        DropDownList1.Items.Add("Florida")
        DropDownList1.Items.Add("Alabama")
    End If


5. You can bind the DropDownList control to an ArrayList. Again, notice that we are not getting the value portion of each option. 

   Dim colArrayList as New System.Collections.ArrayList() 

    If Not Page.IsPostBack Then 
        colArrayList.Add("Georgia")
        colArrayList.Add("Florida")
        colArrayList.Add("Alabama")

        DropDownList1.DataSource = colArrayList 
        DropDownList1.DataBind() 
    End If


6. The following example shows how to populate the control using a Hashtable. Now we can get both the text and value portions populated. 

    Dim myHashTable as new System.Collections.Hashtable() 

    myHashTable("GA") = "Georgia"
    myHashTable("FL") = "Florida"
    myHashTable("AL") = "Alabama"

    For each Item in myHashTable 
        Dim newListItem as new ListItem()
        newListItem.Text = Item.Value 
        newListItem.Value = Item.Key 
        DropDownList1.Items.Add(newListItem) 
    Next 


7. A SortedList is a collection that stores key/value pairs (like a hashtable) but where the items are automatically sorted according to key/value. Here is an example: 

    Dim mySortedList as new System.Collections.SortedList 
    Dim Item as DictionaryEntry 

    mySortedList("GA") = "Georgia"
    mySortedList("FL") = "Florida"
    mySortedList("AL") = "Alabama"

    For each Item in mySortedList 
        Dim newListItem as new ListItem()
        newListItem.Text = Item.Value 
        newListItem.Value = Item.Key 
        DropDownList1.Items.Add(newListItem)
    Next 


8. Here is an example of how you might populate the control from a SQL Server database using a data reader object: 

    ' Let's assume the connection string is stored in a session variable. 
    Dim strConnect as Strng 
    strConnect = Session("ConnectionString") 

    ' Open the Connection 
    Dim Con as new System.Data.SQLClient.SQLConnection(strConnect) 
    Con.Open() 

    ' SQL Statement
    Dim strSQL as String 
    strSQL = "SELECT State_Name, State_Code FROM TableState ORDER BY State_Name"

    ' Command, Data Reader  
    Dim Com as new System.Data.SQLClient.SQLCommand(strSQL, Con) 
    Dim rdr as System.Data.SQLClient.SQLDataReader = Com.ExecuteReader() 

    ' Populate the Control 
    While rdr.Read()
        Dim newListItem as new ListItem() 
        newListItem.Text = rdr.GetString(0)
        newListItem.Value = rdr.GetString(1) 
        DropDownList1.Items.Add(newListItem) 
    End While    

Conclusion
I certainly didn't exhaust all the possibilities but I think this provides a pretty decent overview of the control, how to use it and how to get data into it. If you have any comments, corrections or other ideas, you can email me at
RogerMcCook@hotmail.com.

Roger D. McCook
McCook Software, Inc.


Dig Deeper on VB 6 to VB .NET Migration

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchCloudComputing

SearchSoftwareQuality

TheServerSide.com

Close