Showing posts with label CheckBox. Show all posts
Showing posts with label CheckBox. Show all posts

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