首先在aspx界面中拖入三個DropDownList控件,分別右鍵屬性前兩個控件,把 AutoPostBack 改為 True ,Items點擊添加在txt中輸入請選擇,并把Value的值改為0,再點擊事件按鈕把前兩個控件添加SelectedIndexChanged事件。
數據庫的設計,列名有 id(自增長) ParentId Name,如圖

進入cs界面,在Page_Load中寫如下代碼
PRotected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { getProdata();//省(直轄市) getcitydata();//市 getquxiandata();//縣 } }
然后在前兩個DropDownList控件下寫SelectedIndexChanged事件,代碼如下
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { getcitydata();//市 getquxiandata();//縣 } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { getquxiandata();//縣 }再寫 getProdata();//省(直轄市) getcitydata();//市 getquxiandata();//縣 方法的代碼
public void getProdata()//省、直轄市 { var query = dc.dt.Where(p => p.ParentId == 0); if (query.Count() !=0) { DropDownList1.DataSource = query;//綁定數據之前先清除之前數據 DropDownList1.DataTextField = "Name"; DropDownList1.DataValueField = "id"; DropDownList1.DataBind(); } else { DropDownList1.Text = "無數據"; } } public void getcitydata()//市 { string name1 = DropDownList1.SelectedValue;//獲取選中值的ID var query = dc.dt.Where(p => p.ParentId == int.Parse(name1)); if (query.Count() != 0) { DropDownList2.DataSource = query; DropDownList2.DataTextField = "Name"; DropDownList2.DataValueField = "id"; DropDownList2.DataBind(); } else { DropDownList2.SelectedIndex = 0; } } public void getquxiandata()//縣 { string name2 = DropDownList2.SelectedValue;//獲取選中值的ID var query = dc.dt.Where(p => p.ParentId == int.Parse(name2)); if (query.Count() != 0) { DropDownList3.DataSource = query; DropDownList3.DataTextField = "Name"; DropDownList3.DataValueField = "id"; DropDownList3.DataBind(); } else { DropDownList3.SelectedIndex = 0; } }完成


新聞熱點
疑難解答