ASP.NET - Dropdown List with Values from Database
It is often needed to get input from the user from a predefined list of values available
in a database. For this we will be using dropdown list control available in ASP.NET.
We need to use the following procedure:
- Place a dropdown list control in the form.

- Set these important properties. Normally we will display the text information to
the user, whereas we will store the Id of the selected value in the database or
for various calculations. Hence we will normally use the Varchar field for the DataTextField
and DataValueField respectively.

- Write the following code in order to bind the table data to the dropdown list. Normally
we will do this in Page Load event as shown below:
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim dt As DataTable
dt = GetDataTable("Select ProductId, ProductName " & _
"From Products Order By ProductName")
ddlProduct.DataSource = dt
ddlProduct.DataBind()
End If
End Sub
- Whenever you want to display the selected text or value, or want to take into calculation,
use the code like the one shown below. In this sample, we are taking the result
and showing in the label.
Protected Sub btnShowSelectedValue_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnShowSelectedValue.Click
If ddlProduct.SelectedIndex = -1 Then
lblResult.Text = "You've not selected any item. " & _
"Please select it and try again!"
Else
lblResult.Text = ddlProduct.SelectedItem.Text & " - " & _
ddlProduct.SelectedItem.Value
End If
End Sub
- Run to view the result as shown below. In the following result, 6 is the Product
Id value of the selected product and the other one is Product Name.

- Run to view the result.
Inserting a predefine value along with Database Table values.
Sometimes it necessary to show the first record, which often means
no value is selected. In order to achieve this, we can insert an item after binding the resultset as shown
below:
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim dt As DataTable
dt = GetDataTable("Select ProductId, ProductName " & _
"From Products Order By ProductName")
ddlProduct.DataSource = dt
ddlProduct.DataBind()
ddlProduct.Items.Insert(0, "Choose Product")
End If
End Sub
The above code will give the following result.

|