Sunday, August 28, 2011

Persisting CheckBox State While Paging in GridView Control

grid

Default.aspx
----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxPersistGridView.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:GridView ID="gvCustomers" PageSize="3" AllowPaging="true" OnPageIndexChanging="gvCustomersPageChanging" runat="server" AutoGenerateColumns="false">
    
    <Columns>
    
    <asp:TemplateField>
    <ItemTemplate>
    <asp:CheckBox ID="chkSelect" runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="First Name">
    <ItemTemplate>
    <%# Eval("CatID") %>
    </ItemTemplate>
    </asp:TemplateField>
    
     <asp:TemplateField HeaderText="Last Name">
    <ItemTemplate>
    <%# Eval("CatName") %>
    </ItemTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="RowIndex">
    <ItemTemplate>
    <%# Container.DisplayIndex  %>
    </ItemTemplate>
    </asp:TemplateField>
    
      <asp:TemplateField HeaderText="DataItemIndex">
    <ItemTemplate>
    <%# Container.DataItemIndex  %>
    </ItemTemplate>
    </asp:TemplateField>
    
    </Columns>
    
    </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Default.aspx.cs
--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace CheckBoxPersistGridView
{
    public partial class Default : System.Web.UI.Page
    {
        public const string SELECTED_CUSTOMERS_INDEX = "SelectedCustomersIndex"; 
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                BindData();
            }
        }
        private void BindData()
        {
            SqlConnection conn = new SqlConnection(@"Data Source=truefaster\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            conn.Open();
            SqlCommand cmd = new SqlCommand("select CatID,CatName from Category",conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Category");
            gvCustomers.DataSource = ds.Tables["Category"];
            gvCustomers.DataBind();
            //using(var db = new  NorthwindDataContext())
            //{
                
            //    gvCustomers.DataSource = from c in db.Categories
            //                             select c; 
            //    gvCustomers.DataBind();
            //}
            RePopulateCheckBoxes(); 
        }
        private void RePopulateCheckBoxes()
        {
            foreach (GridViewRow row in gvCustomers.Rows)
            {
                var chkBox = row.FindControl("chkSelect") as CheckBox;
                IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
                if (SelectedCustomersIndex != null)
                {
                    if (SelectedCustomersIndex.Exists(i => i == container.DataItemIndex))
                    {
                        chkBox.Checked = true;
                    }
                }
            }
        }
        protected void gvCustomersPageChanging(object sender, GridViewPageEventArgs e)
        {
            foreach(GridViewRow row in gvCustomers.Rows)
            {
                var chkBox = row.FindControl("chkSelect") as CheckBox;
                IDataItemContainer container = (IDataItemContainer) chkBox.NamingContainer; 
                if(chkBox.Checked)
                {
                    PersistRowIndex(container.DataItemIndex); 
                }
                else
                {
                    RemoveRowIndex(container.DataItemIndex);
                }
            }
            gvCustomers.PageIndex = e.NewPageIndex;
            BindData(); 
        }
        private List<Int32> SelectedCustomersIndex
        {
            get
            {
                if(ViewState[SELECTED_CUSTOMERS_INDEX] == null)
                {
                    ViewState[SELECTED_CUSTOMERS_INDEX] = new List<Int32>(); 
                }
                return (List<Int32>) ViewState[SELECTED_CUSTOMERS_INDEX]; 
            }
        }
        private void RemoveRowIndex(int index)
        {
            SelectedCustomersIndex.Remove(index); 
        }
        
        private void PersistRowIndex(int index)
        {
            if(!SelectedCustomersIndex.Exists(i => i == index))
            {
                SelectedCustomersIndex.Add(index);
            }
        }
    }
}



output:


0 comments:

Post a Comment