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

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. }

你可能感兴趣的:(.net,UI,XHTML,asp.net,asp)