Home ] Up ] Syllabus ] Resources ] Tools ] Assignments ] Announcement ]

Example of Pre-Selecting a Data-Driven Dropdown list box 

Dropdown List Box

 

You can enter a category in the Textbox and then click on the Button labeled "Select Default Category ID" to set the default selection of the dropdown list box . 

 

==== Source Code Listing ===

<%@ Page Language="VB" %>

<%@ import Namespace="System.Data.OleDb" %>

<%@ import Namespace="System.Data" %>

<script runat="server">

Sub Page_Load( ByVal sender As System.Object, ByVal e As System.EventArgs)

If Not ISPostBack Then

Dim conn As OleDbConnection

conn = New _
OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" &  _
"Data Source=" & Server.MapPath("Northwind.mdb") )

Dim ds As DataSet = New DataSet()

Dim da As OleDbDataAdapter = New _

OleDbDataAdapter("select CategoryID, CategoryName from Categories ORDER BY CategoryName", conn)

da.Fill(ds, "Categories")

' Use a DataView as a DataSource

DropDownList1.DataSource = ds

DropDownList1.DataMember = "Categories"

DropDownList1.DataTextField = "CategoryName"

DropDownList1.DataValueField = "CategoryID"

Page.DataBind()

End If

End Sub

Sub ButtonSubmit_Click(sender As Object, e As EventArgs)

Label1.Text = "Category name selected is " + DropDownList1.SelectedItem.Text

Label1.Text &= "<br>Category ID selected is " + DropDownList1.SelectedItem.Value

End Sub

Sub ButtonSetCategoryID_Click(sender As Object, e As EventArgs)

DropDownList1.SelectedValue = TextBoxCID.Text

Label1.Text = "Default category name set is " + DropDownList1.SelectedItem.Text

Label1.Text &= "<br>Default category ID set is " + TextBoxCID.Text

End Sub

</script>

<html>

<head>

</head>

<body>

<form runat="server">

<p>

Category:

<asp:DropDownList id="DropDownList1" runat="server" Width="157px"></asp:DropDownList>

</p>

<p>

<asp:Button id="ButtonSubmit" onclick="ButtonSubmit_Click" runat="server" Text="Submit"></asp:Button>

</p>

<p>

Category ID Chosen:

<asp:TextBox id="TextBoxCID" runat="server"></asp:TextBox>

</p>

<p>

<asp:Button id="ButtonSetCategoryID" onclick="ButtonSetCategoryID_Click" runat="server"
Text="Select Default Category ID"></asp:Button>

</p>

<p>

<asp:Label id="Label1" runat="server"></asp:Label>

</p>

<!-- Insert content here -->

</form>

</body>

</html>