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

被折叠的 条评论
为什么被折叠?



