• How to maintain CheckBox state while paging GridView in C#

    by  • April 29, 2014 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET • 0 Comments

    GridView is a famous and probably most used control to display data on a webpage. When we have large number of records, we can do paging in GridView. We normally use checkboxes in GridView to select rows but when we change page index then we lose our previous page selected rows. Sometimes we need to keep previous pages selected rows as well so that we can use all selected rows. In this article, I will show you the code to maintain the state of selected checkboxes. First we need to keep selected rows indexes or Ids in an object so that we can get these when we will change page index.

    I have written three methods for this article. First method is to get data. You can get data from database or any other data source and bind it to GridView. Here, I am creating a DataTable dynamically and binding it to GridView. Second method is to save the state of selected checkboxes in a session object so that I can get these values from session object when I need it. In the third method, I am repopulating the saved state of checkboxes and this will maintain the state of selected rows after page index changed. You need to call these methods in GridView PageIndexChanging event so that the state of CheckBoxes can be saved before index changed. Now let’s see the code.

    Create a website in Visual Studio and add a web form

    Add a GridView control with following attributes, BoundFields and a CheckBox control

    Write following method to get and bind data.

    Now write this method to save the state of selected checkboxes

    Write another method to populate the saved state of the checkboxes

    Now call GetEmployees() method in Page Load event

    At the end, call these methods and set the page index in PageIndexChanging event

    You can download complete code from below link

    Best WordPress Themes and Plugins with Great Team and Support!

    Avatar of GetCodeSnippet.com


    GetCodeSnippet.com provides you high quality Microsoft .NET development related articles, tutorials and sample code for ASP.NET, C#, VB.NET, AJAX, WCF, WPF, Web Services, Windows Services, SQL Server and other technologies.

    Leave a Reply