Add DropDownList items programmatically in code behind« View all ASP.net articles
December 18, 2006
There are many instances where adding list items in code behind is the preferable method over adding it in form view.
Drag a DropDownList from the toolbox and rename it ddlMyList.

This is the source code.
<asp:DropDownList ID="ddlMyList" runat="server">
</asp:DropDownList>
Add the items to the Page_Load sub. In this example DropDownList item "Item 1" was added:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.ddlMyList.Items.Add(New ListItem("Item 1"))
End Sub
The above code will create "Item 1" to be both the label and value of the list item. Here is the HTML code when you compile and run the page.
<select name="ddlMyList" id="ddlMyList">
<option value="Item 1">Item 1</option>
</select>
To have a different list item label and value add the following:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.ddlMyList.Items.Add(New ListItem("Label 1", "Value 1"))
End Sub
The new HTML code when you compile and run the page.
<select name="ddlMyList" id="ddlMyList">
<option value="Value 1">Label 1</option>
</select>
Advanced Example: Add list items using a loop
We will add Label 1 through Label 5 using a loop. We will also use the loop to create the value of each item list.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim i As Integer
If Not Page.IsPostBack Then ' to make sure items do not get added again after postback
For i = 1 To 5
Me.ddlMyList.Items.Add(New ListItem("Label " & i, "Value " & i))
Next
End If
End Sub
|