This tutorial shows how we can dynamically populate a dropdown menu from data pulled from a database. VB version.
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 |
We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!
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> |
Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!
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 |
Looking for the C#.NET 2005 Version? Click Here!
Looking for more ASP.NET Tutorials? Click Here!