The following code selects the records from a Microsoft Access database and binds them to a dropdownlist. The Access database is called 'Members' and has a table called 'tblMembers'. The database is located in the folder 'H:\Documents and Settings\Website\members.mdb'.
The codesnippet will retrieve both the fields 'ID' and 'FirstName' and assign ID to the DataValueField of the DropDownList and assign the FirstName to the DataTextField property of the DropDownList. The DataTextField values are those visible in the dropdownlist.
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data.Oledb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub Page_Load()
'declare and initialize our variables
Dim ConnString As String = "Provider=Microsoft.Jet.Oledb.4.0; Data Source= H:\Documents and Settings\Website\members.mdb"
Dim SQL As String = "SELECT ID, FIRSTNAME FROM tblMembers"
Dim Connection As New OleDbConnection(ConnString)
Dim Command As New OleDbCommand(SQL, Connection)
Connection.Open()
Dim DataReader As OleDbDataReader = Command.ExecuteReader()
DropDownList1.Datasource = DataReader
DropDownList1.DataBind()
DataReader.Close()
Connection.Close()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Bind DataReader to DropDownList</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" DataValueField="ID" DataTextField="FirstName">
</asp:DropDownList>
</div>
</form>
</body>
</html>
Get the best asp web hosting provider now and save 30%
Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.