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

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

你可能感兴趣的:(asp.net,server,null,asp,c#)