Thursday, June 14, 2012

How to maintain selected Checkboxes state while paging in GridView?


This is common problem- When we implement paging in GridView then it doesn't maintain selected record when you change page index in GridView.
 

Workaround-   

To solve this problem, we can maintain selected records using ViewState variable and after rebinding Grid we can again make those checkboxes selected. For this we have to maintain code in OnCheckedChanged() and PageIndexChanging() events. 

Here I am explaining - How to maintain selected Check-boxes state while paging in GridView?
 

In this example, I have taken one ViewState["SelectedRows"] variable and one List<string> variable. The purpose of using ViewState["SelectedRows"] variable in this example is that- to maintain selected values in GridView.

There are 2 main steps for this task-

1. While selecting value in GridView, I am string those values in View State variable
2. After rebinding GridView, I am  getting selected values from View State variable and setting in GridView.

Here is code-
 

.aspx code-
 
<table>
            <tr>
                <td>
                    <asp:GridView ID="GridEmpData" runat="server" AutoGenerateColumns="false" Width="300px"
                        AllowPaging="True" PageSize="5" OnPageIndexChanging="GridEmpData_PageIndexChanging">
                        <Columns>
                            <asp:TemplateField HeaderText="Select">
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkEmp" runat="server" OnCheckedChanged="chkEmp_OnCheckedChanged" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Emp Id">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Emp Name">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpName" runat="server" Text='<%# Eval("name") %>'> </asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
        </table>

 
 I have taken one CheckBox inside ItemTemplate of GridView, using this CheckBox records will be selected. I have bounded one server side event to this CheckBox - chkEmp_OnCheckedChanged().
In this event I have written code to store selected record in View State Variable.

The output of this page will be-


Maintaining selected Checkboxes state while paging


Now .cs code-

 
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Loading data to Grid
            GetData();
        }
    }

    protected void chkInactivate_OnCheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkStatus = (CheckBox)sender;
        GridViewRow selectedrow = (GridViewRow)chkStatus.NamingContainer;

        //Getting selected records from View state
        List<string> selectedItems = null;
        if (ViewState["SelectedRows"] != null)
        {
            selectedItems = (List<string>)ViewState["SelectedRows"];
        }
        else
        {
            selectedItems = new List<string>();
        }

        Label lblEmpId = (Label)selectedrow.FindControl("lblEmpId");

        //If checked then adding to list
        if (chkStatus.Checked)
        {

            selectedItems.Add(lblEmpId.Text);
        }
        //if unchecked then remove from list if exist
        else
        {
            var result = selectedItems.Find(item => item == lblEmpId.Text);

            if (result != null)
            {
                selectedItems.Remove(lblEmpId.Text);
            }
        }

        //Assigning Selected records to ViewState
        ViewState["SelectedRows"] = selectedItems;
    }

    //Function to Fill Grid
    private void GetData()
    {
        try
        {
            SqlConnection cn = new SqlConnection("connection string");
            cn.Open();
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter("select id,name  from tablename", cn);
            da.Fill(ds);
            GridEmpData.DataSource = ds;
            GridEmpData.DataBind();
        }
        catch (Exception)
        { 
            throw;
        }
    
    }

    protected void GridEmpData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridEmpData.PageIndex = e.NewPageIndex;
      
        //Loading data to Grid
        GetData();

        //Code to maintain selected record while paging
        if (ViewState["SelectedRows"] != null)
        {
            List<string> selectedItems = (List<string>)ViewState["SelectedRows"];
            foreach (GridViewRow row in GridEmpData.Rows)
            {
                Label lblEmpId = (Label)row.FindControl("lblEmpId");
                var result = selectedItems.Find(item => item == lblEmpId.Text);
                if (result != null)
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkEmp");
                    if (chk != null)
                    {
                        chk.Checked = true;
                    }
                }
            }
        }
    }
 


In above code, First I am binding GridView using GetData() function in page_Load() event.

In OnCheckedChanged() event of CheckBox, first I am getting selected record from View State variable, and after that I am adding newly selected record into View State variable. Suppose if any record is already present then I am removing from View State variable, For this operation I am using List<string>, using List<string> records are adding  and deleting.Finally I am assigning List<string> variable to ViewState.

In PageIndexChanging () event, I have written logic for GridView paging, Here I am setting new page index for paging in GridView. In this event only after rebinding GridView, I am getting selected record from View State variable and assign to GridVIew.


Note- It you want to prevent postback then you can make use of AJAX, for this put your GridView inside the UpdatePanel.




Thanks


20 comments:

  1. Hello, thanks for your example. One disadvantage about this way is that every state change of any Checkbox control will cause a Postback of the whole web page immediately.

    ReplyDelete
  2. Yes, But if you don't want to make PostBack for whole page then make use of Ajax UpdatePanel, Put your Grid inside UpdatePanel. Then it will not refresh whole page.



    ReplyDelete
  3. Hi, nice article..anyway, could you please give an example how to solve this problem if we using AJAX, like you said "Put your Grid inside UpdatePanel. Then it will not refresh whole page".
    couse i'm newbie in ASP and ajax,

    thanks

    ReplyDelete
  4. Thanks you so much, realy greate help...

    ReplyDelete
  5. thank you so much

    ReplyDelete
  6. Replies
    1. HI Anand,

      The above code is working code only, check r u missing anything?

      Delete
  7. Howdy! I just wish to offer you a big thumbs up for the great information you have got right here on this post.
    I will be returning to your site forr more soon.


    Also visit my web site: vérification documents ()

    ReplyDelete
  8. ӏ have read some eҳcellent stuff here. Definigely priϲe bokmarking for revisitіnǥ.
    I ԝonder how а lot atempt you put to make such
    a wonderful informative site.

    Here is my website: vérification curriculum vitae

    ReplyDelete
  9. Please let me know if you're looking for
    a author for your blog. You have some really great articles and I believe I would be a
    good asset. If you ever want to take some of the load off, I'd love to write some content for your blog in exchange
    for a link back to mine. Please shoot me an e-mail if interested.
    Thanks!

    Look into my web blog ... good summer drink; ,

    ReplyDelete
  10. ' Square Enix is going to provide new trailers and
    give attendees a chance to try the playable demos for both products.
    In the free Android app, 'Plague, Inc', your goal is to build a disease that ill destroy humanity.
    Yesterday he succumb to the sickness and peacefully passed away iin confort from his family (at
    his home).

    Visit my site; final fantasy vi android download

    ReplyDelete
  11. Grеat pߋst. I was checking cοnstɑntly this blog аnd I'm
    іmpresѕed! Extremely useful infߋ particularly
    the last part :) I care for such iոformation much. I was seeking
    this particսlar information for a very long time.
    Thank you and best of luсҡ.

    Here is my web-site; recrutement assistant président

    ReplyDelete
  12. Attractiѵe portion of content. I simplʏ stumbleɗ
    upon your web site and in accessiοn capitаl to asѕert that I
    get in fact enjoyed account youhr bloǥ posts. Any way I'll be subscribing in your feeds or even I achievement you get entrfy to persiѕtently fast.


    Hеre is myy web page pure garcinia cambogia in stores

    ReplyDelete
  13. If you want to take a great deal from this piee oof
    writing then you have to apply these techniques to your
    won web site.

    Also visit my web blog: audit sécurité informatique pdf

    ReplyDelete