ASP.NET中获取CheckBoxList的当前选择项

CheckBoxList选中项变化监测
本文介绍了一种监测ASP.NET中CheckBoxList控件选中项变化的方法。通过将选中状态保存在ViewState中,并在SelectedIndexChanged事件中比较前后状态,从而实现对选中项变化的准确捕捉。
CheckBoxList中有多个项,当选择/不选择某项时如果其AutoPostBack为True,则会触发SelectedIndexChanged,但是CheckBoxList及其Items属性都没有直接能获取当前选择的项的属性,想了一下,可以先将上一次的勾选状态存到ViewState中,在触发SelectedIndexChanged的时候进行比较,具体代码如下:
  1. <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="WebApplication1._Default"%>
  2. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <htmlxmlns="http://www.w3.org/1999/xhtml">
  4. <headrunat="server">
  5. <title>无标题页</title>
  6. </head>
  7. <body>
  8. <formid="form1"runat="server">
  9. <div>
  10. <asp:CheckBoxListID="CheckBoxList1"runat="server"AutoPostBack="True"
  11. onprerender="CheckBoxList1_PreRender"
  12. onselectedindexchanged="CheckBoxList1_SelectedIndexChanged"
  13. RepeatDirection="Horizontal">
  14. <asp:ListItem>1</asp:ListItem>
  15. <asp:ListItem>2</asp:ListItem>
  16. <asp:ListItemSelected="True">3</asp:ListItem>
  17. <asp:ListItem>4</asp:ListItem>
  18. <asp:ListItem>5</asp:ListItem>
  19. </asp:CheckBoxList>
  20. </div>
  21. </form>
  22. </body>
  23. </html>
  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. namespaceWebApplication1
  4. {
  5. publicpartialclass_Default:System.Web.UI.Page
  6. {
  7. protectedvoidPage_Load(objectsender,EventArgse)
  8. {
  9. Dictionary<int,bool>dic=newDictionary<int,bool>();
  10. for(inti=0;i<CheckBoxList1.Items.Count;i++)
  11. dic.Add(i,CheckBoxList1.Items[i].Selected);
  12. if(ViewState["cblChecked"]==null)
  13. ViewState["cblChecked"]=dic;
  14. }
  15. protectedvoidCheckBoxList1_SelectedIndexChanged(objectsender,EventArgse)
  16. {
  17. if(ViewState["cblChecked"]!=null)
  18. {
  19. Dictionary<int,bool>dic=ViewState["cblChecked"]asDictionary<int,bool>;
  20. for(inti=0;i<CheckBoxList1.Items.Count;i++)
  21. {
  22. if(dic[i]!=CheckBoxList1.Items[i].Selected)
  23. Response.Write("当前操作项为:"+i.ToString());
  24. dic[i]=CheckBoxList1.Items[i].Selected;
  25. }
  26. ViewState["cblChecked"]=dic;
  27. }
  28. }
  29. }
  30. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值