Navigator: Home - Advanced - Populate DropDown List from Database in ASP.NET & VB

Populate DropDown List from Database in ASP.NET & VB

This tutorial shows how we can dynamically populate a dropdown menu from data pulled from a database. VB version.

Download the Full Working Version of this Project written with Visual Studio.NET VB 2005 Here!

Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

It is often useful to allow users to select items from a dropdown list for input into a web form. However, this can be somewhat too limiting in certain situations.
This tutorial will show how we can dynamically populate a dropdown menu with records from a database.
First, we start by declaring the assembly reference:

Imports System.Data.SqlClient

In our Web.config, we declare the connection string:

<appSettings>
<add key="ConnString" value="Data Source=CLIENT-TASK2\SQLEXPRESS;Initial Catalog=BasicDataAccess;Integrated Security=True"/>
</appSettings>

The ASPX page will look something like this:

<form id="form1" runat="server">
<div align="center">
<table><tr><th>Name:</th><td><asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList></td></tr>
<tr><th>City:</th><td><asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList></td></tr></table>
</div>
</form>

In the code-behind, we can create two methods and then call them on page load:

Imports System.Data.SqlClient

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Populate1()
Populate2()
End Sub

Public Sub Populate1()
Dim cmd As New SqlCommand("SELECT * FROM [tblOne]", New SqlConnection(ConfigurationManager.AppSettings("ConnString")))
cmd.Connection.Open()

Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()

DropDownList1.DataSource = ddlValues
DropDownList1.DataValueField = "theName"
DropDownList1.DataTextField = "theName"
DropDownList1.DataBind()

cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub

Public Sub Populate2()
Dim cmd As New SqlCommand("SELECT * FROM [tblOne]", New SqlConnection(ConfigurationManager.AppSettings("ConnString")))
cmd.Connection.Open()

Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()

DropDownList2.DataSource = ddlValues
DropDownList2.DataValueField = "theCity"
DropDownList2.DataTextField = "theCity"
DropDownList2.DataBind()

cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub
End Class

Download the Full Working Version of this Project written with Visual Studio.NET VB 2005 Here!

Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!
411asp.net123aspxDotNetFreaksServer Intellect