Wednesday, 12 March 2014

Maintain The State Of Checkbox After Postback (Inside GridView)

Hi Friends,in this article i will explain about How to Maintain The State Of Checkbox After Postback (Inside GridView).
I already explained in the previous articles about How to Maintain selected Checkboxes state while paging in GridView?,Filter and Sorting in GridView using DataView in ASP.NET using C#/VB.NET and JQuery:Select Multiple records in GridView with Ctrl Key in ASP.NET using C#/VB.NET.
Write the following code in ASP.NET
ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Maintain The State Of Checkbox After Postback (Inside GridView)</title>
</head>


<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GvEmpDetails" runat="server" DataKeyNames="Id" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#CC9966" BorderStyle="Solid" BorderWidth="1px"
            CellPadding="4" Font-Names="Georgia" Font-Size="Small" Width="375px" OnRowUpdating="GvEmpDetails_RowUpdating"
            OnRowEditing="GvEmpDetails_RowEditing" OnRowCancelingEdit="GvEmpDetails_RowCancelingEdit">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" />
                <asp:BoundField DataField="EMPName" HeaderText="EMPName" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged"
                            OnDataBinding="CheckBox1_DataBinding" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" ShowCancelButton="true" ButtonType="Link" />
            </Columns>
            <FooterStyle BackColor="Tan" />
            <AlternatingRowStyle BackColor="#E6E6E1" />
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

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

    }

    public void BindGrid()
    {
        if (Session["strTemp"] != null)
        {

            GvEmpDetails.DataSource = Session["strTemp"] as DataTable;
            GvEmpDetails.DataBind();

        }
        else
        {
            GvEmpDetails.DataSource = GetCustomMadeDataTable();
            GvEmpDetails.DataBind();
        }


    }
    public DataTable GetCustomMadeDataTable()
    {


        //Create a new DataTable object
        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");
        DataColumn[] dcPk = new DataColumn[1];
        dcPk[0] = objDataTable.Columns["Id"];
        objDataTable.PrimaryKey = dcPk;
        Session["strTemp"] = objDataTable;


        return objDataTable;
    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkbox = (CheckBox)sender;
        if (checkbox.Checked)
        {
            ViewState[checkbox.UniqueID] = true;
        }
        else
        {
            ViewState.Remove(checkbox.UniqueID);
        }
    }

    protected void CheckBox1_DataBinding(object sender, EventArgs e)
    {
        CheckBox checkbox = (CheckBox)sender;
        checkbox.Checked = ViewState[checkbox.UniqueID] != null;
    }
    protected void GvEmpDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        int productID = Convert.ToInt32(((TextBox)(GvEmpDetails.Rows[e.RowIndex].Cells[0].Controls[0])).Text);
        string str1 = ((TextBox)(GvEmpDetails.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
        DataTable dt = Session["strTemp"] as DataTable;

        DataRow[] rows = dt.Select("Id = " + productID);
        rows[0]["EMPName"] = str1;
        GvEmpDetails.EditIndex = -1;
        BindGrid();

    }
    protected void GvEmpDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GvEmpDetails.EditIndex = e.NewEditIndex;
        BindGrid();

    }
    protected void GvEmpDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GvEmpDetails.EditIndex = -1;
        BindGrid();

    }

}

VB.NET:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

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

    End Sub

    Public Sub BindGrid()
        If Session("strTemp") IsNot Nothing Then

            GvEmpDetails.DataSource = TryCast(Session("strTemp"), DataTable)

            GvEmpDetails.DataBind()
        Else
            GvEmpDetails.DataSource = GetCustomMadeDataTable()
            GvEmpDetails.DataBind()
        End If


    End Sub
    Public Function GetCustomMadeDataTable() As DataTable


        'Create a new DataTable object
        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")
        Dim dcPk As DataColumn() = New DataColumn(0) {}
        dcPk(0) = objDataTable.Columns("Id")
        objDataTable.PrimaryKey = dcPk
        Session("strTemp") = objDataTable


        Return objDataTable
    End Function
    Protected Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs)
        Dim checkbox As CheckBox = DirectCast(sender, CheckBox)
        If checkbox.Checked Then
            ViewState(checkbox.UniqueID) = True
        Else
            ViewState.Remove(checkbox.UniqueID)
        End If
    End Sub

    Protected Sub CheckBox1_DataBinding(sender As Object, e As EventArgs)
        Dim checkbox As CheckBox = DirectCast(sender, CheckBox)
        checkbox.Checked = ViewState(checkbox.UniqueID) IsNot Nothing
    End Sub
    Protected Sub GvEmpDetails_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)

        Dim productID As Integer = Convert.ToInt32(DirectCast(GvEmpDetails.Rows(e.RowIndex).Cells(0).Controls(0), TextBox).Text)
        Dim str1 As String = DirectCast(GvEmpDetails.Rows(e.RowIndex).Cells(1).Controls(0), TextBox).Text
        Dim dt As DataTable = TryCast(Session("strTemp"), DataTable)

        Dim rows As DataRow() = dt.[Select]("Id = " & productID)
        rows(0)("EMPName") = str1
        GvEmpDetails.EditIndex = -1
        BindGrid()

    End Sub
    Protected Sub GvEmpDetails_RowEditing(sender As Object, e As GridViewEditEventArgs)
        GvEmpDetails.EditIndex = e.NewEditIndex
        BindGrid()

    End Sub
    Protected Sub GvEmpDetails_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
        GvEmpDetails.EditIndex = -1
        BindGrid()

    End Sub

End Class


The output of the above code is as shown in the below figure. Checkboxes after postback also maintain the state.

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.