DropDownList Selection
Posted by David Wier on 04/16/10 | Code Samples
Just copy and paste this code into a new blank page. This is example uses MS Access. Just change the location of the database on your computer to use this code. If you want to use the pubs database with SQL Server, change the whole Provider connection string, command and the imported namespace.
‘ Code Behind: Imports System.Data Import System.Data.OleDb
Protected Sub Page_Load(ByVal Source As Object, ByVal E As EventArgs)
If Not IsPostBack Then BindData() End If End Sub
Protected Sub button1_click(ByVal Source As Object, ByVal E As EventArgs) label1.Text = " You selected " & MyList.SelectedItem.Text End Sub
Protected Sub Reset_Click(ByVal Source As Object, ByVal E As EventArgs) label1.Text = "" BindData() End Sub
Protected Sub BindData() Dim strSQL As String Dim strConn As String strSQL = "Select distinct city from publishers where city <>''" strConn = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" & _ Server.MapPath("~\App_Data\BIBLIO.MDB") & ";" Dim Conn As New OleDbConnection(strConn) Dim Cmd As New OleDbCommand(strSQL, Conn) Conn.Open() MyList.DataSource = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection MyList.DataBind() Conn.Close() End Sub
‘ ASPX page: <html> <head> <title>Dropdown List</title> </head> <body> <div align="center"> <form id="Form1" runat="server"> <asp:DropDownList ID="MyList" DataTextField="city" runat="server" /> <asp:Button ID="button1" Text="Submit" OnClick="button1_click" runat="server" /> <asp:Button ID="Reset" Text="Reset" OnClick="Reset_Click" runat="server" />
</form> <p><b><font color="#800000"> <asp:Label ID="label1" runat="server" /> </font></b></p> </div> </body></html>
|