CheckBoxList中有多个项,当选择/不选择某项时如果其AutoPostBack为True,则会触发SelectedIndexChanged,但是CheckBoxList及其Items属性都没有直接能获取当前选择的项的属性,想了一下,可以先将上一次的勾选状态存到ViewState中,在触发SelectedIndexChanged的时候进行比较,具体代码如下:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>无标题页</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
- onprerender="CheckBoxList1_PreRender"
- onselectedindexchanged="CheckBoxList1_SelectedIndexChanged"
- RepeatDirection="Horizontal">
- <asp:ListItem>1</asp:ListItem>
- <asp:ListItem>2</asp:ListItem>
- <asp:ListItem Selected="True">3</asp:ListItem>
- <asp:ListItem>4</asp:ListItem>
- <asp:ListItem>5</asp:ListItem>
- </asp:CheckBoxList>
- </div>
- </form>
- </body>
- </html>
- using System;
- using System.Collections.Generic;
- namespace WebApplication1
- {
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- Dictionary<int, bool> dic = new Dictionary<int, bool>();
- for (int i = 0; i < CheckBoxList1.Items.Count; i++)
- dic.Add(i, CheckBoxList1.Items[i].Selected);
- if (ViewState["cblChecked"] == null)
- ViewState["cblChecked"] = dic;
- }
- protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
- {
- if (ViewState["cblChecked"] != null)
- {
- Dictionary<int, bool> dic = ViewState["cblChecked"] as Dictionary<int,bool>;
- for (int i = 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;
- }
- }
- }
- }