DropDownList和ListBox实现两级联动功能,它们可以将从后台数据库中搜选的出来的信息加以绑定,这里要实现的功能是在DropDownList中选择“省”,然后让ListBox自动将其省份下的“市”显示出来,这就是所谓的两级联动功能,这个功能我们在很多注册网页上看见,今天就为大家解开ASP.NET神秘的面纱。
一、设置前台界面,在Web窗体中添加DropDownList和ListBox两个控件。
界面图如下所示。
二、编写后台代码
在这,后台代码编写在其窗体的Page_Load事件中
<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自动添加该“省”所具有的“市”
<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>
运行文件,效果图如下所示
这里河北省的城市我没有添加完整,只是为了实现两级联动的功能,相比前两篇文章中Web控件GridView和Repeater的使用,GridView和Repeater功能虽然是相当强大,但是不同的控件有不同的用途,在这里,杀鸡焉用牛刀?
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月25日
2024年09月25日
- 纯音入心系列纯音乐《中央民族乐团-古筝传奇》1CD[MP3][253.1MB]
- 江玲.1989-这样你才爱我,是吗?【新作有声】【WAV+CUE】
- 郭美美.2010-我是郭美美【华纳】【WAV+CUE】
- 黄心懋1991-轻忧郁【滚石】【WAV+CUE】
- 群星.2000-大地金曲世纪回顾2CD【大地】【WAV+CUE】
- 王菲.1996-浮躁(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 群星.2022-传家电视剧原声带【东阳欢娱】【FLAC分轨】
- 《摇滚教父 伍佰黄金精选 2CD》 [WAV+CUE][1GB]
- 《凤凰传奇 我从草原来》[WAV/分轨][400MB]
- 《叶倩文 真心真意过一生》[WAV+CUE][400MB]
- 潘越云.1985-世间女子(滚石25周年经典复刻版)【滚石】【WAV+CUE】
- 陈柏宇.2009-CANT.BE.HALF【SONY】【WAV+CUE】
- 李明依.1989-小女生【滚石】【WAV+CUE】
- 《李荣浩 新时代创作新人王》[WAV分轨][310MB]
- 《黑鸭子与马头琴 史上最动听草原音乐》[WAV+CUE][320MB]