Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Introduction:
In this article I will explain how to maintain state of selected checkboxes during paging in gridview using asp.net
Description:

I have one gridview with checkboxes and it contains lot of data for that reason I applied paging for gridview and displaying 8 records per page. After apply the paging in gridview if I select checkboxes in first page and moving to another page and select some checkboxes in second page after that if I come back I am unable to see the previous selected values. At that time I know one new thing that is gridview won’t maintain the state of controls during postback for that reason we need write some code to maintain the previous selected values in gridview. Before seeing the code implemention first Design your aspx page like this



<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Maintain State Checkboxes during paging</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvdetails" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" onpageindexchanging="gvdetails_PageIndexChanging" PageSize="8" DataKeyNames="UserId">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
After completion of aspx page design add the following references in code behind


using System.Collections;
using System.Data;
using System.Data.SqlClient;



After completion of adding reference write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridData();
}
}
//This method is used to bind the gridview
protected void BindGridData()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
SqlCommand cmd = new SqlCommand("select * from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SaveCheckedValues();
gvdetails.PageIndex = e.NewPageIndex;
BindGridData();
PopulateCheckedValues();
}
//This method is used to populate the saved checkbox values
private void PopulateCheckedValues()
{
ArrayList userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (userdetails != null && userdetails.Count > 0)
{
foreach (GridViewRow gvrow in gvdetails.Rows)
{
int index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
if (userdetails.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
//This method is used to save the checkedstate of values
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in gvdetails.Rows)
{
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;

// Check in the Session
if (Session["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
if (userdetails != null && userdetails.Count > 0)
Session["CHECKED_ITEMS"] = userdetails;
}

If you observe above code I written one method to bind our gridview and written two more methods those are SaveCheckedValues and PopulateCheckedValues these two methods are used to maintain the state of selected checkbox values during paging in gridview. In SaveCheckedValues method I used Session variable to maintain the selected checkbox values after that by using this saved session values I am populating the checkbox state in PopulateCheckedValues method.

Demo

Download sample code attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

35 comments :

Anonymous said...

this is wonderfull, i love u


Vidya

Anonymous said...

Its good...however can u also let me know how to pass the values of all the pages at once in a database..ex: On Page1 i selected 3 values on Page 2 i selected more 2 values...then on click of my SAVE button i should be able to insert Total of 5 values in Database. U can get in touch with my on laghaterohan@gmail.com :)
Happy Coding.!

Suresh said...

yes we can pass all the values into database by checking the which checkbox values are checked out we will pass those values into database this will be do by taking loop for cheking the items in gridview

Shaju said...

can you pls write the code for getting the entire checked checkbox values.eg.in page 1 i have checked 3 checkboxes .in page2 i have 2 checked checkboxes and so on.so that i can save the entire values to a database.If i checked 3 checkboxes in page 1 and i went to page2 and checked 2 checkboxes again i returned to page 1.Will the values repeat again.I want to avoid repetition

manasa said...

Its goood...can u please tell me the code for how to select/deselect all checkboxes while paging and also it should maintain individual check box state.

Suresh Dasari said...

hi manasa check this post here i explain clearly how to select/deselect checkboxes while paging also it will work for you check this post

http://aspdotnet-suresh.blogspot.com/2011/03/how-to-selectdeselect-checkboxes-in.html

Anonymous said...

it help me a lot thankx

Anonymous said...

well done


mohit

Anonymous said...

God bless you. You made my life easy.

Excellent code. But there are two issues here.
1. lets say there are 10 records per page. Let assume that in first page you have records 1 to 10. You select record 9 and 10. Now in the second page you selected check box for record 11 and 12. Once you perform delete in the page 1, 9 & 10 will get deleted (which is correct). Record 11 and 12 will move to page one (which is also correct). But here record 11 and 12 will loose the selection.

To prevent this you need to:
1. Call RePopulateValues() after calling BindData() in the delete button click event.
2. Call RePopulateValues() in the BindData() method as the last statement.

Another issue is when you to other page and come back to this page, since storing the check box state into session, in a few scenarios you might get the check box selected (which is not correct). To prevent this you need to make the session empty as I did:
// Making session empty for check box checked state.
ArrayList categoryIDList = new ArrayList();
Session["CHECKED_ITEMS"] = categoryIDList;

You can do this where you are first time binding the gridview. In my case I have a search button with some filter criteria. On click on search button I am doing this.

AFTER MAKING ABOVE CHANGES, MY CODE IS WORKING PERFECTLY FINE.

Regards,
Krishn Y.

* MOON * said...

how to get this code? no download option exists...

Suresh Dasari said...

hi Moon,
i attach the downloadable code you can download the code from that link

anuraj44 said...

Good Post. Thank u very much

Anonymous said...

i got the error Specified cast is not valid when i run your code in
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;

any solution ????

Anonymous said...

i got the error Specified cast is not valid when i run your code in
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;

Jyothi said...

i got the error Specified cast is not valid when i run your code in
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;

Please help me

Anonymous said...

Superb thanks a lot for sharing this code !!!!!
Exactly what i was looking for.

argunsun

Anonymous said...

really super suresh...
Very thankful to u

Anonymous said...

Hi suresh, this is kavitha. Your code is so expressive and clear. It helps many programmers like me.

Thank you so much.

Subhash Jakhar said...

Hi Suresh
i hav error when save checked value in array list
****************
Unable to cast object of type 'System.String' to type 'System.Collections.ArrayList'.

Line:- userdetails = (ArrayList )Session["CHECKED_ITEMS"];

Plz Give me Solution

Anonymous said...

hi suresh,
i have one error
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;

DINU said...

hi suresh,
i have one error
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;

plz help me

sandy chpos said...

I am getting below error

Instead of calling binddata function

my code is
gridview.DataSourceID = "SqlDataSource1"
gridview.DataBind()

and i ma getting below error :(
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

can you please help me ?

Anonymous said...

Thanks a lot for sharing this valuable code.

Anonymous said...

Please let me know if I want to cont checked Checkbox in DataList with Paginng??? How it can b done???

Anonymous said...

hello

how can remove inside excel seat image and check ox

thanks

Anonymous said...

hello

when i am import data from gridview to excel seat issubscribed image and checkbox icon also show plz tell me how can resolved this issue

thanks

Anonymous said...

Zabardast mean excellent and very simple no xtra work. I like it

akhil said...

LOT OF THANKS TO U MR.SURESH DASARI FOR SUCH A HELPFUL POST...EXPECTING FURTHER FROM U ...:)

SASI said...

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

my code is following:

protected void Grd_Degree_RowUpdating (object sender, GridViewUpdateEventArgs e)
{

string id = Grd_Degree.DataKeys[e.RowIndex].Value.ToString();



SqlDataAdapter da = new SqlDataAdapter("select degree_id,degree_name from Degree where degree_name='" +id+"' ",cn );
DataTable dt2 = new DataTable();
da.Fill(dt2);
int id1=0 ;
for (int i = 0; i < dt2.Rows.Count; i++)
{
id1=Convert.ToInt32 (dt2.Rows[i]["degree_id"]);
}


TextBox txt_degree = (TextBox)Grd_Degree.Rows[e.RowIndex].FindControl("txtdeg");
if (txt_degree.Text != string.Empty)
{
//DBConnector.ClsConnection.getInstance().UpdateData("Update Degree set degree_name='" + txt_degree.Text + "' where degree_id=" + id + "");
SqlDataAdapter da2 = new SqlDataAdapter("Update Degree set degree_name='" + txt_degree.Text + "' where degree_id=" + id1 + "", cn);
DataTable dt22 = new DataTable();
da2.Fill(dt22);
}
Grd_Degree.EditIndex = -1;
fillGrid();

}
ple help me

Sanjay said...

Check Box Status is preserved when the page index is changed at client side but the status of check boxes is not preserved present on last page if grid view. To preserve the status of last page checkboxes we have to go back one page and then post the form

manish arora said...

how to get value of selected checkboxes in grid view with paging?

Roberto Gomez said...

how can i do if i have more than 1 DataKeyNames?? my DataKeyNames is:

DataKeyNames="IdOferta,CódigoArtículoProveedor,WebURL"

and "IdOferta" is the primarykey.

sarvesh muranjan said...

how to maintain state of dropdownlists selection in gridview while paging;plz help I'm tired of googling.

Sai B - AppScienti said...

sir it was getting error gvdetails is used for data source and data bind

Harish Palsule said...

Its very useful for me thank you boss..........

Give your Valuable Comments

Other Related Posts

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