ASP.NET中DropDownList和ListBox实现两级联动功能

2025-05-29 0 36

DropDownListListBox实现两级联动功能,它们可以将从后台数据库中搜选的出来的信息加以绑定,这里要实现的功能是在DropDownList中选择“省”,然后让ListBox自动将其省份下的“市”显示出来,这就是所谓的两级联动功能,这个功能我们在很多注册网页上看见,今天就为大家解开ASP.NET神秘的面纱。
一、设置前台界面,在Web窗体中添加DropDownListListBox两个控件。

界面图如下所示。

ASP.NET中DropDownList和ListBox实现两级联动功能

二、编写后台代码
在这,后台代码编写在其窗体的Page_Load事件中

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
<span style="font-family:KaiTi_GB2312;font-size:18px;"> protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack ) //判断页面是否第一次加载

{

SqlConnection con = DB.createConnection(); //此方法在上一篇文章中已经介绍,调用一个已经编写好的创建数据库连接的方法。

SqlCommand cmd = new SqlCommand("select * from province",con);

SqlDataReader sdr = cmd.ExecuteReader();

this.DropDownList1.DataTextField = "proName";

this.DropDownList1.DataValueField = "proID"; //主键字段

this.DropDownList1.DataSource = sdr;

this.DropDownList1.DataBind();

sdr.Close();

}

}</span>

编写DropDownList1_SelectedIndexChanged事件代码,实现单击“省”,ListBox自动添加该“省”所具有的“市”

?

1

2

3

4

5

6

7

8

9

10

11
<span style="font-family:KaiTi_GB2312;font-size:18px;"> protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

{

this.ListBox1.Items.Clear();

SqlConnection con2 = DB.createConnection();

SqlCommand cmd1 = new SqlCommand("select * from city where proID=" + this.DropDownList1.SelectedValue, con2);

SqlDataReader sdr1 = cmd1.ExecuteReader();

while (sdr1.Read())

{

this.ListBox1.Items.Add(new ListItem(sdr1.GetString(2),sdr1.GetInt32(0).ToString()));

}

}</span>

运行文件,效果图如下所示

ASP.NET中DropDownList和ListBox实现两级联动功能

这里河北省的城市我没有添加完整,只是为了实现两级联动的功能,相比前两篇文章中Web控件GridView和Repeater的使用,GridView和Repeater功能虽然是相当强大,但是不同的控件有不同的用途,在这里,杀鸡焉用牛刀?

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 ASP.NET中DropDownList和ListBox实现两级联动功能 https://www.kuaiidc.com/102059.html

相关文章

发表评论
暂无评论