How to persist checkbox state in gridview while paging

Again an asp.net post. Today I saw the same question few times in forum, so I thought about creating a post around it. And it helped me to brush up my asp.net skills once again. In this I am using ViewState to store the information about paging state, you can also use session instead of View State. As view state is enabled default and its required for Paging also, I thought better to use ViewState than session.

I created a web page with a Gridview with Paging enabled. First column of the grid view is Template Column which contains the Checkbox for selection of rows. And the state information is saved while paging, and retrived on Prerender event of the GridView. And here is the implementation.

ASPX Markup

<asp:GridView runat="server" ID="gvSample" AutoGenerateColumns="false" AllowPaging="True"
            OnPageIndexChanging="gvSample_PageIndexChanging" OnPreRender="gvSample_PreRender">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox runat="server" ID="chkSelected" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Email" HeaderText="Email" />
            </Columns>
            <PagerSettings PageButtonCount="10" />
        </asp:GridView>

And here is the code-behind for it

protected void gvSample_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    string pageId = string.Format("Page{0}", gvSample.PageIndex);
    bool[] selectedCheckboxes = new bool[gvSample.PageSize];
    for (int i = 0; i < gvSample.Rows.Count; i++)
    {
        TableCell cell = gvSample.Rows[i].Cells[0];
        selectedCheckboxes[i] = (cell.FindControl("chkSelected") as CheckBox).Checked;
    }

    ViewState[pageId] = selectedCheckboxes;
    gvSample.PageIndex = e.NewPageIndex;
    //Bind the gridview again
}

protected void gvSample_PreRender(object sender, EventArgs e)
{
    string pageId = string.Format("Page{0}", gvSample.PageIndex);
    bool[] selectedCheckboxes = ViewState[pageId] as bool[];
    if (selectedCheckboxes != null)
    {
        for (int i = 0; i < gvSample.Rows.Count; i++)
        {
            TableCell cell = gvSample.Rows[i].Cells[0];
            (cell.FindControl("chkSelected") as CheckBox).Checked = selectedCheckboxes[i];
        }
    }
}

Welcome for Feedbacks/Suggestions/Comments. Thank you for reading my blog. Happy Programming :)

4 thoughts on “How to persist checkbox state in gridview while paging

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>