ASP.NET中使用DropDownList实现无刷新二级联动详细过程

 

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

posted @   弎吩锺熱℃  阅读(3800)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示