DropDownList and the listbox to achieve level two linkage function, they can also be selected from the background database of information to bind, the function is to choose "Province" in the DropDownList, and then let the listbox automatically show its province "city", This is the so-called two-level linkage function, this feature we see on many registration pages, today we use ASP to solve its mysterious veil.
First, set up the foreground interface, add DropDownList and ListBox two controls in the Web Form. The interface diagram is shown below.
Second, write the background code
In this case, the background code is written in the Page_Load event of its form
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > protected void Page_Load (object sender, EventArgs e) { if (! Page.IsPostBack) //Determine if the page is loaded for the first time { SqlConnection con = db.createconnection (); This method is described in the previous article, invoking a method that has been written to create a database connection. SqlCommand cmd = new SqlCommand ("select * from Province", con); SqlDataReader SDR = cmd. ExecuteReader (); This. Dropdownlist1.datatextfield = "Proname"; This. Dropdownlist1.datavaluefield = "Proid"; Primary key field this . Dropdownlist1.datasource = SDR; This. Dropdownlist1.databind (); Sdr. Close (); } } </span>
Write the DropDownList1_SelectedIndexChanged event code, implement click "Save", the listbox automatically add the "province" has the "city"
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e) {this . ListBox1.Items.Clear (); SqlConnection Con2 = Db.createconnection (); SqlCommand cmd1 = new SqlCommand ("SELECT * from city where proid=" + this. Dropdownlist1.selectedvalue, con2); SqlDataReader SDR1 = cmd1. ExecuteReader (); while (SDR1. Read ()) {this . LISTBOX1.ITEMS.ADD (New ListItem (SDR1. GetString (2), SDR1. GetInt32 (0). ToString ())); } } </span>
run the file as shown below
Here in Hebei Province I did not add complete, just in order to achieve the two-level linkage function, compared to the first two blogs in the Web control of the GridView and repeater use, the GridView and repeater functionality Although is quite powerful, But different controls have different uses, here, how to kill chicken with sledgehammer?
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
ASP. NET data binding-dropdownlist, ListBox