Home > Article > Backend Development > 'ASP.NET' Data Binding—Detailed Explanation of Graphic and Text Codes for DropDownList and ListBox
DropDownList and ListBox implement a two-level linkage function. They can also bind the information selected from the background database. The function to be implemented here is to select "Province" in the DropDownList, and then let the ListBox automatically Displaying the "city" under its province is the so-called two-level linkage function. We have seen this function on many registration web pages. Today we will use ASP.NET to unravel its mystery.
1. Set up the front-end interface and add DropDownList and ListBox controls to the Web form. The interface diagram is shown below.
# # 2. Write the background code
Here, 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 ) //判断页面是否第一次加载 { SqlConnection con = DB.createConnection(); //此方法在上一篇文章中已经介绍,调用一个已经编写好的创建数据库连接的方法。 SqlCommand cmd = new SqlCommand("select * from province",con); SqlDataReader sdr = cmd.ExecuteReader(); this.DropDownList1.DataTextField = "proName"; this.DropDownList1.DataValueField = "proID"; //主键字段 this.DropDownList1.DataSource = sdr; this.DropDownList1.DataBind(); sdr.Close(); } }</span>
Write the code for the DropDownList1_SelectedIndexChanged event to realize that when you click "province", the ListBox automatically adds the "city" owned by the "province"
#
<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, the effect is as shown below
GridView and Repeater in the first two blogs, Although the functions of GridView and Repeater are quite powerful, different controls have different uses. How can one kill a chicken with a big knife here?
The above is the detailed content of 'ASP.NET' Data Binding—Detailed Explanation of Graphic and Text Codes for DropDownList and ListBox. For more information, please follow other related articles on the PHP Chinese website!