DropDownList:

The DropDownList is one of my favorite contols. It takes up a small space on your page and allows the user to select from a list of items. You can either hand-type this list in manually or you can create a DataSource of information and then "bind" the control to the DataSource. (Choose from Access Database, SQL Database, XML file, etc. then Select a DataField to display then Select a Value for the Data)

How to detect which item was selected from the dropdownlist

When you have many controls on a page, you may not want to get the selected answer immediately but instead wait until a submit button is clicked. In this scenerio, you add the code to the button event. But when you do want an immediate answer, add AutoPostBack="True" to the dropdownlist See the results of this in the dropdown list shown here:

This ddl was created using the Edit Items:


ASP.NET

        
  <asp:dropdownlist id="ddlFruitList" runat="server" AutoPostBack="true" /> 
        

VB.NET

        
  Protected Sub ddlFruit_SelectedIndexChanged(ByVal sender As Object, 
       ByVal e As System.EventArgs) Handles ddlFruit.SelectedIndexChanged 

   Dim YourFruit As String = ddlFruitList.SelectedValue 
   lblFruit.Text = "You picked " + YourFruit 

  End Sub

<asp:dropdownlist id="ddlFruitList" runat="server" AutoPostBack="true" /> 
        

Build your DropDownList

You have several options for adding the text into the dropdownlist properties. Listed below are just 3 of the many options you have available.

OPTION 1: Type the name for each list item directly into the dropdownlist in your ASP.NET web page.

        
        <asp:dropdownlist id="myFirstList" runat="server" /> 

        

OPTION 2: Type the list in code-behind (VB.NET or C#) using an array

 

        
  DropDownList1.Items.Clear()
  
  Dim months() As String {"January","February","March","April","May","June", 
           "July", "August", "September", "October", "November", "December"}
   
  DropDownList1.DataSource = months  
  DropDownList1.DataBind()       
        

OPTION 3: Get your list from a datasource (ie. database, etc.) and bind it to a DataSource control.

        
 <asp:dropdownlist id="myFirstList" runat="server"
         DataSourceId="srcMovies" DataTextField="Title" />
 
 <asp:SqlDataSource id=srcMovies" ConnectionString="Data Source=.\SQLExpress;
       AttachDbFilename=|DataDirectory| MyMovieDatabase.mdf;
       Integrated Security=True; User Instance=True"
       SelectCommand="SELECT Title FROM Movies" runat="server" />
        

*Notice the ID of the SqlDataSource is the same as the DataSourceId of the dropdownlist.