The DropDownList and ListBox implement level two linkage function. They can also bind the information that is picked up from the background database. The function to be implemented here is to select "Province" in the DropDownList, and then let the listbox take the initiative to show the "city" under its province, this is called the two-level linkage function, which we see on the very many register page. Today we are going to use ASP to unravel its magical veil.
First, set the foreground interface, add DropDownList and ListBox two controls in the web window. The interface diagram is seen in the following example.
Second, write the background code
In this case, the background code is written in the Page_Load event of its window
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > protected void Page_Load (object sender, EventArgs e) { if (! Page.IsPostBack) //Infer 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 "Province", the listbox to voluntarily join 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>
execute the file, as seen in the following
Here in Hebei Province I did not join the complete, just 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 features, although quite powerful, However, different controls have different uses. How do you use sledgehammer to kill chickens here?
ASP. NET data binding-dropdownlist, ListBox