標籤:
Demo.sql
1 create table Car( 2 [id] int identity, 3 [brand] varchar(50) not null, 4 [type] varchar(50) not null 5 ) 6 go 7 8 insert into Car ([brand],[type])values(‘BMW‘,‘B‘),(‘BMW‘,‘M‘),(‘BMW‘,‘W‘), 9 (‘BENZ‘,‘B‘),(‘BENZ‘,‘E‘),(‘BENZ‘,‘N‘),(‘BENZ‘,‘Z‘),10 (‘HONDA‘,‘H‘),(‘HONDA‘,‘O‘),(‘HONDA‘,‘N‘),(‘HONDA‘,‘D‘),(‘HONDA‘,‘A‘),11 (‘TOYOTA‘,‘T‘),(‘TOYOTA‘,‘O‘),(‘TOYOTA‘,‘Y‘),(‘TOYOTA‘,‘A‘)
Demo.aspx
1 <asp:ScriptManager runat="server"> 2 </asp:ScriptManager> 3 <asp:UpdatePanel runat="server"> 4 <ContentTemplate> 5 <asp:DropDownList ID="dropBrand" runat="server" OnSelectedIndexChanged="dropBrand_SelectedIndexChanged" 6 Width="200" AutoPostBack="True"> 7 </asp:DropDownList> 8 <asp:DropDownList ID="dropType" runat="server" Width="200"> 9 </asp:DropDownList>10 </ContentTemplate>11 </asp:UpdatePanel>
Demo.aspx.cs
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 if (!IsPostBack) 4 { 5 BindDrop(); 6 } 7 } 8 9 private void BindDrop()10 {11 //將資料捆綁到下拉式清單中12 string sqlStr = "select distinct [brand] from Car";13 DataTable dt = SqlHelper.ExecuteDataTable(sqlStr);14 dropBrand.DataTextField = "brand"; //設定列表顯示的字15 dropBrand.DataValueField = "brand"; //設定列表提交後獲得的欄位,自己理解為隱藏綁定資料16 dropBrand.DataSource = dt;17 dropBrand.DataBind();18 dropBrand.Items.Insert(0, new ListItem("請選擇車子品牌", ""));//第一項中加入內容,重點是綁定後添加19 dropType.Items.Insert(0, new ListItem("請選擇車子品牌型號", ""));//第一項中加入內容,重點是綁定後添加 20 }21 22 protected void dropBrand_SelectedIndexChanged(object sender, EventArgs e)23 {24 string sqlStr = "select * from Car where [brand]=‘" + dropBrand.SelectedValue + "‘";//頁面載入後dropBrand.DataValueField隱藏繫結資料,後邊根據它查詢dropType要顯現的資料25 DataTable dt = SqlHelper.ExecuteDataTable(sqlStr);26 dropType.DataTextField = "type"; //設定dropBrand事件SelectedIndexChanged改變後dropType列表顯示的資料27 dropType.DataValueField = "id";28 dropType.DataSource = dt;29 dropType.DataBind();30 }
參考原文:http://www.cnblogs.com/cqchai/archive/2011/05/28/2061378.html
ASP.NET中使用DropDownList實現無重新整理二級聯動詳細過程