Demo.sqlhtml
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.aspxsql
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.cside
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.htmlspa