Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

Maintaining State of CheckBoxes While Paging in a GridView

Article:
Viewed:  3812 
Posted On:  31/01/2013 09:40:33 
In this article I am going to show how we can maintain CheckBox state in GridView while Paging 

In this article I am going to explain how we can maintain selected checkbox state in GridView while paging.

When we bind record like in below image

MaintainCheckBoxState_1.png
Image 1.

When move to 2nd page after selecting some record on 1st page..

MaintainCheckBoxState_2.png

Image 2.

Now we are on 2nd page and now move to 1st page..

MaintainCheckBoxState_3.png

Image 3.

Selected checkbox remain selected while we came here from 2nd page to 1st page.

Below is my aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Maintain CheckBox Values GridView Paging </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="2" cellspacing="2" width="50%" align="center">
            <tr>
                <td align="center" bgcolor="#FFFFFF">
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
                        AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" CellPadding="4"
                        PageSize="4" ForeColor="#333333" GridLines="None" DataKeyNames="ID">
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <Columns>
                            <asp:TemplateField HeaderText="Select">
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkSelect" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="ID" HeaderText="ID" />
                            <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                            <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                            <asp:BoundField DataField="JoiningDate" HeaderText="Join Date" />
                        </Columns>
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <EditRowStyle BackColor="#999999" />
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    </asp:GridView>
                    <asp:Label ID="lblStatus" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
 

This is my aspx.cs code

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Collections;
 
public partial class _Default : System.Web.UI.Page
{
    SqlDataAdapter da;
    DataSet ds = new DataSet();
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }
 
    private void BindData()
    {
        SqlConnection con = new SqlConnection("Server=.;Database=MyData;Uid=sa; pwd=India@123");
        SqlCommand cmd = new SqlCommand("SELECT ID, FirstName,LastName,JoiningDate FROM Employee", con);
        try
        {
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
 
            if (!object.Equals(ds.Tables[0], null))
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    GridView1.DataSource = ds.Tables[0];
                    GridView1.DataBind();
                    Session["MyTable"] = ds.Tables[0];
                }
                else
                {
                    GridView1.DataSource = null;
                    GridView1.DataBind();
                }
            }
            else
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }
        catch (Exception ex)
        {
            lblStatus.Text = ex.Message;
        }
    }
  

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        KeepChecks();
        GridView1.PageIndex = e.NewPageIndex;
        BindData();
        ApplyChecks();
    }
 
    private void KeepChecks()
    {
        ArrayList chkList = new ArrayList();
        int index = -1;
        foreach (GridViewRow gvrow in GridView1.Rows)
        {
            index = (int)GridView1.DataKeys[gvrow.RowIndex].Value;
            bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;
           
            if (Session["RemindChecks"] != null)
                chkList = (ArrayList)Session["RemindChecks"];
            if (result)
            {
                if (!chkList.Contains(index))
                    chkList.Add(index);
            }
            else
                chkList.Remove(index);
        }
        if (chkList != null && chkList.Count > 0)
            Session["RemindChecks"] = chkList;
    }
 
 
    private void ApplyChecks()
    {
        ArrayList chkList = (ArrayList)Session["RemindChecks"];
        if (chkList != null && chkList.Count > 0)
        {
            foreach (GridViewRow gvrow in GridView1.Rows)
            {
                int index = (int)GridView1.DataKeys[gvrow.RowIndex].Value;
                if (chkList.Contains(index))
                {
                    CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
                    myCheckBox.Checked = true;
                }
            }
        }
    }
}

  Comment:
 
By dheeraj  On  16/02/2015 22:53:08
i got an error index out of range what i do?? urgent plz tell me
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us