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. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5.     <title>无标题页</title>
  6. </head>
  7. <body>
  8.     <form id="form1" runat="server">
  9.     <div>
  10.         
  11.         <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True" 
  12.             onprerender="CheckBoxList1_PreRender" 
  13.             onselectedindexchanged="CheckBoxList1_SelectedIndexChanged" 
  14.             RepeatDirection="Horizontal">
  15.             <asp:ListItem>1</asp:ListItem>
  16.             <asp:ListItem>2</asp:ListItem>
  17.             <asp:ListItem Selected="True">3</asp:ListItem>
  18.             <asp:ListItem>4</asp:ListItem>
  19.             <asp:ListItem>5</asp:ListItem>
  20.         </asp:CheckBoxList>
  21.     </div>
  22.     </form>
  23. </body>
  24. </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. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值