Sunday, 20 April 2014

How to Maintain selected Checkboxes state while paging in GridView?

Hi friends,in this article i will explain about How to Maintain selected Checkboxes state while paging in GridView?
I already explained in the previous articles about Filter and Sorting in GridView using DataView in ASP.NET using C#/VB.NET,JQuery:Select Multiple records in GridView with Ctrl Key in ASP.NET using C#/VB.NET and How to change link button text in GridView at Runtime in ASP.NET using C#/VB.NET.
ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to Maintain selected Checkboxes state while paging in GridView?</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridEmpDetails" runat="server" AutoGenerateColumns="false" BackColor="White"
            BorderColor="#CC9966" BorderStyle="Solid" BorderWidth="1px" CellPadding="4" Font-Names="Georgia"
            Font-Size="Small" Width="375px" AllowPaging="True" PageSize="5" OnPageIndexChanging="GridEmpDetails_PageIndexChanging">
            <Columns>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkActive" runat="server" OnCheckedChanged="chkActive_OnCheckedChanged" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emp Id">
                    <ItemTemplate>
                        <asp:Label ID="lblEmpId" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emp Name">
                    <ItemTemplate>
                        <asp:Label ID="lblEmpName" runat="server" Text='<%# Eval("EMPName") %>'> </asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="Tan" />
            <AlternatingRowStyle BackColor="#E6E6E1" />
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        </asp:GridView>
        <asp:Button ID="btnpost" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

In C#:
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
using System.Collections.Generic;

public partial class MaintainStatePaging : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }

    protected void chkActive_OnCheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkStatus = (CheckBox)sender;
        GridViewRow selectedrow = (GridViewRow)chkStatus.NamingContainer;
        List<string> selectedItems = null;
        if (ViewState["SelectedCheckBoxes"] != null)
        {
            selectedItems = (List<string>)ViewState["SelectedCheckBoxes"];
        }
        else
        {
            selectedItems = new List<string>();
        }

        Label lblEmpId = (Label)selectedrow.FindControl("lblEmpId");

        if (chkStatus.Checked)
        {
            selectedItems.Add(lblEmpId.Text);
        }
        else
        {
            var result = selectedItems.Find(item => item == lblEmpId.Text);

            if (result != null)
            {
                selectedItems.Remove(lblEmpId.Text);
            }
        }

        ViewState["SelectedCheckBoxes"] = selectedItems;
    }

    private void BindData()
    {
        try
        {
            System.Data.DataTable objDataTable = new System.Data.DataTable();
            objDataTable.Columns.AddRange(new DataColumn[2] { new DataColumn("Id"), new DataColumn("EMPName") });
            objDataTable.Rows.Add("1", "Kishore");
            objDataTable.Rows.Add("2", "Satya");
            objDataTable.Rows.Add("3", "Satyam");
            objDataTable.Rows.Add("4", "Raghava");
            objDataTable.Rows.Add("5", "Nag");
            objDataTable.Rows.Add("6", "Krishna");
            objDataTable.Rows.Add("7", "Purna Anil");
            objDataTable.Rows.Add("8", "Sowji");
            objDataTable.Rows.Add("9", "Abhi");
            objDataTable.Rows.Add("10", "Sreenu");
            objDataTable.Rows.Add("11", "Ashok");
            objDataTable.Rows.Add("12", "Sathish");
            objDataTable.Rows.Add("13", "Purna");
            GridEmpDetails.DataSource = objDataTable;
            GridEmpDetails.DataBind();
        }
        catch (Exception)
        {
            throw;
        }

    }

    protected void GridEmpDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridEmpDetails.PageIndex = e.NewPageIndex;
        BindData();

        //Code to maintain selected checkbox state while paging
        if (ViewState["SelectedCheckBoxes"] != null)
        {
            List<string> selectedItems = (List<string>)ViewState["SelectedCheckBoxes"];
            foreach (GridViewRow row in GridEmpDetails.Rows)
            {
                Label lblEmpId = (Label)row.FindControl("lblEmpId");
                var result = selectedItems.Find(item => item == lblEmpId.Text);
                if (result != null)
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkActive");
                    if (chk != null)
                    {
                        chk.Checked = true;
                    }
                }
            }
        }
    }

}

In VB.NET:
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls
Imports System.Collections.Generic

Partial Public Class MaintainStatePaging
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            BindData()
        End If
    End Sub

    Protected Sub chkActive_OnCheckedChanged(sender As Object, e As EventArgs)
        Dim chkStatus As CheckBox = DirectCast(sender, CheckBox)
        Dim selectedrow As GridViewRow = DirectCast(chkStatus.NamingContainer, GridViewRow)
        Dim selectedItems As List(Of String) = Nothing
        If ViewState("SelectedCheckBoxes") IsNot Nothing Then
            selectedItems = DirectCast(ViewState("SelectedCheckBoxes"), List(Of String))
        Else
            selectedItems = New List(Of String)()
        End If

        Dim lblEmpId As Label = DirectCast(selectedrow.FindControl("lblEmpId"), Label)

        If chkStatus.Checked Then
            selectedItems.Add(lblEmpId.Text)
        Else
            Dim result = selectedItems.Find(Function(item) item = lblEmpId.Text)

            If result IsNot Nothing Then
                selectedItems.Remove(lblEmpId.Text)
            End If
        End If

        ViewState("SelectedCheckBoxes") = selectedItems
    End Sub

    Private Sub BindData()
        Try
            Dim objDataTable As New System.Data.DataTable()
            objDataTable.Columns.AddRange(New DataColumn(1) {New DataColumn("Id"), New DataColumn("EMPName")})
            objDataTable.Rows.Add("1", "Kishore")
            objDataTable.Rows.Add("2", "Satya")
            objDataTable.Rows.Add("3", "Satyam")
            objDataTable.Rows.Add("4", "Raghava")
            objDataTable.Rows.Add("5", "Nag")
            objDataTable.Rows.Add("6", "Krishna")
            objDataTable.Rows.Add("7", "Purna Anil")
            objDataTable.Rows.Add("8", "Sowji")
            objDataTable.Rows.Add("9", "Abhi")
            objDataTable.Rows.Add("10", "Sreenu")
            objDataTable.Rows.Add("11", "Ashok")
            objDataTable.Rows.Add("12", "Sathish")
            objDataTable.Rows.Add("13", "Purna")
            GridEmpDetails.DataSource = objDataTable
            GridEmpDetails.DataBind()
        Catch generatedExceptionName As Exception
            Throw
        End Try

    End Sub

    Protected Sub GridEmpDetails_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
        GridEmpDetails.PageIndex = e.NewPageIndex
        BindData()

        'Code to maintain selected checkbox state while paging
        If ViewState("SelectedCheckBoxes") IsNot Nothing Then
            Dim selectedItems As List(Of String) = DirectCast(ViewState("SelectedCheckBoxes"), List(Of String))
            For Each row As GridViewRow In GridEmpDetails.Rows
                Dim lblEmpId As Label = DirectCast(row.FindControl("lblEmpId"), Label)
                Dim result = selectedItems.Find(Function(item) item = lblEmpId.Text)
                If result IsNot Nothing Then
                    Dim chk As CheckBox = DirectCast(row.FindControl("chkActive"), CheckBox)
                    If chk IsNot Nothing Then
                        chk.Checked = True
                    End If
                End If
            Next
        End If
    End Sub
End Class

The output of the above page as shown in the below figure.I checked one one checkbox in each page.The state checkboxes is maintaine.After clicking 3rd checkbox in the 3rd when you click on first page the first checkbox shows checked.
You can download the code by clicking on the below Download image.

No comments:

Post a Comment

© 2012-2014 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.