通过Ajax技术对DropDrowList控件联动改变应用
改变一个DropDrowList会引起另一个DropDrowList的值改变:
Page Code:
<table> <tr> <th>省份</th> <td> <asp:DropDownList ID="drpProvice" runat="server" onselectedindexchanged="drpProvice_SelectedIndexChanged" AutoPostBack="True"> </asp:DropDownList> </td> <th>城市</th> <td><asp:DropDownList ID="drpCity" runat="server"> </asp:DropDownList></td> </tr> </table>
Class Code:
protected void Page_Load(object sender,EventArgs e) { if (!IsPostBack) { InitData(); } } protected virtual Int32 StringToInt32(string val,Int32 defaultVal) { int tmp = 0; if (Int32.TryParse(val,out tmp)) { return tmp; } return defaultVal; } public sqlConnection Open() { string strConn = ConfigurationManager.ConnectionStrings["MysqLDataBase"].ConnectionString; sqlConnection conn = new sqlConnection(strConn); conn.Open(); return conn; } public void Close() { sqlConnection conn = Open(); conn.Close(); } private void InitData() { ProviceBind(); Citybind(); } private void ProviceBind() { string strsql = "select * from Ajax_Provice"; sqlConnection conn = Open(); sqlDataAdapter da = new sqlDataAdapter(strsql,conn); DataSet ds = new DataSet(); da.Fill(ds); drpProvice.DataSource = ds.Tables[0]; drpProvice.DataTextField = "c_provName"; drpProvice.DataValueField = "c_provId"; drpProvice.DataBind(); //drpTypeId.Items.Insert(0,new ListItem("全部","")); } private void Citybind() { int temp = StringToInt32(drpProvice.SelectedValue,0); string strsql = "select * from Ajax_City Where c_provId = {0}"; strsql = string.Format(strsql,temp); sqlConnection conn = Open(); sqlDataAdapter da = new sqlDataAdapter(strsql,conn); DataSet ds = new DataSet(); da.Fill(ds); drpCity.DataSource = ds.Tables[0]; drpCity.DataTextField = "c_city"; drpCity.DataValueField = "c_provId"; drpCity.DataBind(); Close(); } protected void drpProvice_SelectedIndexChanged(object sender,EventArgs e) { Citybind(); }当然只有这些代码,是不行的,要记住一点要把DropDrowList的属性 AutoPostBack设置为"True",不然不会有联动的效果哦。
数据库图: