【原创】用UpdatePanel实现无刷新级联下拉框
使用asp.net ajax扩展实现无刷新下拉列表可实现你要的效果,此种方法不用写js
1.在项目中引用asp.net ajax扩展dll,附件中有(关于此扩展,参见http://www.cnblogs.com/Terrylee/archive/2006/11/12/ASPNET_AJAX_QuickStarts.html)
此处主要使用asp:UpdatePanel 实现
2.使用测试用表结构如下
表province 字段 id provincename
表city 字段 id provincename cityname
3.代码如下
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%@ Import Namespace = "System.Data" %> <%@ Import Namespace = "MySql.Data.MySqlClient" %> <script language="C#" runat="server"> //页面载入 protected void Page_Load(object sender, EventArgs e) { If(!IsPostBack) { getProvince(); } } //得到省 private void getProvince() { MySqlConnection myConnection = new MySqlConnection("server=localhost;userid=root;password=root;database=test"); string sql = "select t.provincename from province t"; MySqlDataAdapter myda = new MySqlDataAdapter(sql, myConnection); DataSet mydataset = new DataSet(); myda.Fill(mydataset, "admin"); DropDownList1.DataSource = mydataset.Tables[0].DefaultView; DropDownList1.DataTextField = "provincename"; DropDownList1.DataValueField = "provincename"; DropDownList1.DataBind(); getCity(DropDownList1.SelectedValue); } //根据省得到市 private void getCity(String s) { MySqlConnection myConnection = new MySqlConnection("server=localhost;userid=root;password=root;database=test"); string sql = "select t.cityname from city t where t.provincename = '" + s + "'"; MySqlDataAdapter myda = new MySqlDataAdapter(sql, myConnection); DataSet mydataset = new DataSet(); myda.Fill(mydataset, "admin"); DropDownList2.DataSource = mydataset.Tables[0].DefaultView; DropDownList2.DataTextField = "cityname"; DropDownList2.DataValueField = "cityname"; DropDownList2.DataBind(); } //改变省时 private void changeProvince(object sender, EventArgs e) { getCity(DropDownList1.SelectedValue); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Simple MySQL Database Query</title></head> <body> <form runat="server"> <asp:DataGrid id="mydatagrid" runat="server" /> <!--此处AutoPostBack设为true时,才会对DropDownList2进行刷新--> <asp:DropDownList id="DropDownList1" runat="server" OnSelectedIndexChanged="changeProvince" AutoPostBack="true"> </asp:DropDownList> <!--使用UpdatePanel之前必须放置ScriptManager,必须引用asp.net ajax包--> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <!--必须将DropDownList放入UpdatePanel内才可对其刷新--> <asp:UpdatePanel id="cityPanel" runat="server" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" /> </Triggers> <ContentTemplate> <asp:DropDownList id="DropDownList2" runat="server" AutoPostBack="true"></asp:DropDownList> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>