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