DropDownList and ListBox to achieve two-level linkage, they can be selected from the background database of the information to bind, here to achieve the function is to select the "Province" in the DropDownList, and then let the listbox automatically in its province under the "City" display, This is called the two-level linkage function, which we see on many registered Web pages, today for everyone to unlock the veil of asp.net mystery.
First , set the foreground interface and add DropDownList and ListBox two controls to the Web form.
The interface diagram is shown below.
Second, the preparation of 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)//To determine whether the page was first loaded
{
SqlConnection con = db.createconnection ();//This method is described in the previous article, Invokes 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 dropdownlist1_selectedindexchanged event code, implementation click "Province", the listbox automatically add the "Province" of 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 in the image below
The city of Hebei province I did not add complete, just in order to achieve the two-level linkage function, compared to the first two articles in the Web control GridView and repeater use, the GridView and Repeater function is quite powerful, but different controls have different uses, here, How to kill a chicken with a sledgehammer?