Click here to Skip to main content
15,879,326 members
Articles / Web Development / ASP.NET

How to select multiple records from a GridView and persist the selection during pagination

Rate me:
Please Sign up or sign in to vote.
4.84/5 (13 votes)
27 May 2011CPOL3 min read 72.2K   26   9
In this article, we are going to learn how to select multiple records from a GridView and persist the selection during pagination.

Introduction

The GridView control has a property called AllowPaging which enables us to paginate GridView records. So to enable pagination for a GridView, set the AllowPaging property to true and we will need to also handle the OnPageIndexChanging event. The PagerSettings-Mode property displays the page numbers to navigate through different pages of the GridView records.

The OnRowDataBound event is raised when the data is bound to the GridView control. This enables us to provide an event-handling method that can be used to access the GridView rows one by one and perform the desired operation.

This solution is one of many solutions provided in .NET How to's.

The following code snippet from the ASPX page shows how these properties and events are set.

ASPX Page

ASP.NET
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
  AllowPaging="true" DataKeyNames="AutoId" OnPageIndexChanging="PaginateTheData" 
  PageSize="5" PagerSettings-Mode="Numeric 
  OnRowDataBound="ReSelectSelectedRecords">
    <Columns> 
                <asp:TemplateField HeaderText="Select"> 
                    <ItemTemplate> 
                        <asp:CheckBox ID="chkSelect" runat="server" /> 
                    </ItemTemplate> 
                </asp:TemplateField> 
                <asp:BoundField HeaderText="AutoId" DataField="AutoId" /> 
                <asp:BoundField HeaderText="First Name" DataField="FirstName" /> 
                <asp:BoundField HeaderText="Last Name" DataField="LastName" /> 
                <asp:TemplateField HeaderText="Is Active?"> 
                    <ItemTemplate> 
                        <%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
                    </ItemTemplate> 
                </asp:TemplateField> 
            </Columns>  
        </asp:GridView> 
<p><asp:Button ID="btnGetSelected" runat="server" 
   Text="Get Selected Records" OnClick="GetSelectedRecords" /></p>

In the above code snippet, we have a GridView and a Button. In the GridView, we have added the OnRowDataBound event that fires the ReSelectSelectedRecords server side event. As we have set AutoGenerateColumns to false, we are explicitly writing the columns of the GridView. The first column will have the CheckBox that will be used by the user to select the GridView record.

Code Behind

C#
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)
{ 
    if (!IsPostBack) 
    { 
        this.GetData(); 
    } 
} 

/// <summary> 
/// Paginates the data. 
/// </summary> 
/// <param name="sender">The sender.</param> 
/// <param name="e">The <seecref="System.Web.UI.WebControls.GridViewPageEventArgs"/>
///       instance containing the event data.</param> 

protected void PaginateTheData(object sender, GridViewPageEventArgs e) 
{ 
    List<int> list = new List<int>(); 
    if (ViewState["SelectedRecords"] != null) 
    { 
        list = (List<int>)ViewState["SelectedRecords"]; 
    } 
    foreach (GridViewRow row in GridView1.Rows) 
    { 
        CheckBox chk = (CheckBox)row.FindControl("chkSelect"); 
        var selectedKey = 
        int.Parse(GridView1.DataKeys[row.RowIndex].Value.ToString()); 
        if (chk.Checked) 
        { 
            if (!list.Contains(selectedKey)) 
            { 
                list.Add(selectedKey); 
            } 
        } 
        else 
        { 
            if (list.Contains(selectedKey)) 
            { 
                list.Remove(selectedKey); 
            } 
        } 
    } 
    ViewState["SelectedRecords"] = list; 
    GridView1.PageIndex = e.NewPageIndex; 
    this.GetData(); 
} 

/// <summary> 
/// Gets the data. 
/// </summary> 
private void GetData() 
{ 
    DataTable table = new DataTable(); 
    // get the connection 
    using (SqlConnection conn = new SqlConnection(_connStr)) 
    { 
        // write the sql statement to execute 
        string sql = "SELECT AutoId, FirstName, LastName, Age, Active " + 
                         "FROM PersonalDetail ORDER By AutoId"; 
        // instantiate the command object to fire 
        using (SqlCommand cmd = new SqlCommand(sql, conn)) 
        { 
            // get the adapter object and attach the command object to it 
            using (SqlDataAdapter ad = new SqlDataAdapter(cmd)) 
            { 
                // fire Fill method to fetch the data and fill into DataTable 
                ad.Fill(table); 
            } 
        } 
    } 
    GridView1.DataSource = table; 
    GridView1.DataBind(); 
} 

/// <summary> 
/// Gets the selected records. 
/// </summary> 
/// <param name="sender">The sender.</param> 
/// <param name="e">The <see cref="System.EventArgs"/>
///    instance containing the event data.</param> 
protected void GetSelectedRecords(object sender, EventArgs e) 
{ 
    Response.Write("<h3>Selected records</h3>"); 
    List<int> list = ViewState["SelectedRecords"as List<int>; 
    if (list != null) 
    { 
        foreach (int id in list) 
        { 
            Response.Write(id.ToString() + "<br />"); 
        } 
    } 
} 

/// <summary> 
/// Looks for selection. 
/// </summary> 
/// <param name="sender">The sender.</param> 
/// <param name="e">The <seecref="System.Web.UI.WebControls.GridViewRowEventArgs"/>
///     instance containing the event data.</param> 
protected void ReSelectSelectedRecords(object sender, GridViewRowEventArgs e) 
{ 
    List<int> list = ViewState["SelectedRecords"as List<int>; 
    if (e.Row.RowType == DataControlRowType.DataRow && list != null) 
    { 
        var autoId = int.Parse(GridView1.DataKeys[e.Row.RowIndex].Value.ToString()); 
        if (list.Contains(autoId)) 
        { 
            CheckBox chk = (CheckBox)e.Row.FindControl("chkSelect"); 
            chk.Checked = true; 
        } 
    } 
}

When the page loads, the records are populated into the GridView under the Not IsPostBack condition.

PaginateTheData() method

When the page numbers link of the GridView is clicked, the PaginateTheData method fires that checks for the selected records by looping through all the rows of the GridView and finding the checkbox checked status. If the checkbox is checked, that item is added into the list (a Generic List collection of integer data type) and if not, we are making sure that it has been removed in case the user had checked earlier and paginated and now has unchecked.

To persist the checkbox checked status, we need a mechanism to save the selected records so that in the next paging post back, we can retrieve it. For this purpose, we have saved the checked (selected) records into the Generic collection (list) and saved into the ViewState.

If the user is navigating to other pages, we need to make sure that the selected record's ID is saved into the List and ultimately stored into the ViewState, so for that purpose, we check for the existing selected records and add the newly selected records into the collection and save into the ViewState.

The last part of this method sets the newly selected page index and re-populates the data to the GridView.

ReSelectSelectedRecords() method

This method fires on the OnRowDataBound event and retrieves the currently selected records from the ViewState and checks the checkbox of the records if it was previously selected.

GetSelectedRecords() method

This method fires on the click of the button and retrieves the selected records from the ViewState, loops through, and prints it on the screen.

Now when we run this page, we get output as shown below:

img1.JPG

On the first page, the records with AutoID 3 and 5 have been selected.

img2.JPG

On the second page, the record with AutoId 14 has been selected. Now when we navigate to the first page again, notice that the checkbox status is persisted and the records with AutoId 3 and 5 are checked. On the click of the button, all the checked records' AutoIds are printed on the page.

This article has been written based on this ITFunda.com article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer ITFunda
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGet Selected Records does not get tje last selected solution Pin
tarikonal4-Mar-20 20:39
tarikonal4-Mar-20 20:39 
GeneralClean and simple. Pin
Washington Morais3-Sep-14 8:09
Washington Morais3-Sep-14 8:09 
GeneralMy vote of 5 Pin
spencepk3-Jul-13 8:16
spencepk3-Jul-13 8:16 
SuggestionNot paging not ViewState updated Pin
DiegoDuarteG13-Sep-12 6:09
DiegoDuarteG13-Sep-12 6:09 
SuggestionThis was great. One minor suggestion Pin
Steinmetzma15-Jul-12 21:17
Steinmetzma15-Jul-12 21:17 
GeneralRe: This was great. One minor suggestion Pin
MacSpudster18-Sep-12 8:37
professionalMacSpudster18-Sep-12 8:37 
GeneralRe: This was great. One minor suggestion Pin
Member 1054524423-Jan-14 11:32
Member 1054524423-Jan-14 11:32 
QuestionThank you! Pin
sallemann30-Dec-11 7:38
sallemann30-Dec-11 7:38 
GeneralMy vote of 5 Pin
Sheo Narayan27-May-11 22:48
Sheo Narayan27-May-11 22:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.