|
Dropdown Lists from Database
by Charles Carroll
This page demonstrates the capabilities
to bind listboxes to databases. Notice the datavalue attribute and datatext
attribute. The former can be used to provide values that do not match the
displayed value (like relational keys in databases).
This example uses a Access/OLEDB
data source.
An example using SQL7/2000 is at
http://www.aspng.com/learn/dblistsqlclient.aspx.
filename=\experiments\databinding\oledbdropdown.aspx
<%@ Import Namespace="System.Data.OLEDB" %>
<script language="VB" runat="server">
Sub Page_Load(Src As Object, E As EventArgs)
Dim strConn as string ="PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" & server.mappath("/experiments/data/biblio.mdb") & ";"
Dim Conn1 as OLEDBConnection
Dim Rdr1 as OLEDBDatareader
Dim Cmd1 as OLEDBCommand
Dim strSQL as string
Conn1=New OLEDBConnection(strConn)
strSQL="select distinct city from publishers"
Cmd1=New OLEDBCommand(strSQL,Conn1)
Conn1.Open()
Rdr1=Cmd1.ExecuteReader()
cy.DataSource = Rdr1
cy.DataBind()
Rdr1.close()
strSQL="select distinct state from publishers"
Cmd1.commandtext=strSQL
Rdr1=Cmd1.ExecuteReader()
st.DataSource = Rdr1
st.DataBind()
Rdr1.Close()
strSQL="select distinct zip from publishers"
Cmd1.commandtext=strSQL
Rdr1=Cmd1.ExecuteReader()
zp.DataSource = Rdr1
zp.DataBind()
Rdr1.Close()
Conn1.close()
End Sub
</script>
<html><head>
<title>Dropdowns</title>
</head>
<body bgcolor="#FFFFFF">
<form runat="server">
<asp:Table runat="server" GridLines="both" BorderWidth="1px">
<asp:TableRow>
<asp:TableCell>City</asp:TableCell>
<asp:TableCell><ASP:DropDownList id="cy" datatextfield="city" runat="server"/>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>State</asp:TableCell>
<asp:TableCell><ASP:DropDownList id="st" datatextfield="state" runat="server"/>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>Zip</asp:TableCell>
<asp:TableCell><ASP:DropDownList id="zp" datatextfield="zip" runat="server"/>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</form>
</body></html>
|