Click here to Skip to main content
16,020,305 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I successfully added the code to my page for maintaining the state of check boxes in grid view during pagination but got a very different issue. if I select some check boxes on the first page and than go on second page and select some check boxes there and return back to first page, what I see is that there are more number of check boxes selected automatically as compared to I did. I don't know where I am going wrong !
I exactly followed the logic and code snippet as in this link :

Maintaining States of Selected CheckBoxes in Different Pages inside the GridView[^]

Can anyone please help me,,,It is really urgent and important for my project.
Thank you
Posted
Updated 24-Jul-12 20:14pm
v3

This can be done a variety of ways, but basically everytime a CheckBox is checked, you must save its state somewhere that it is now Checked or Unchecked. Then after every re-bind of your data, you can pull this state out of the Session or ViewState and re-set the state of the CheckBoxes. Here's an example of how I would maintain the state:

ASPX:
ASP.NET
<asp:gridview id="gvProducts" runat="server" allowpaging="True" autogeneratecolumns="False" xmlns:asp="#unknown">
datakeynames="ProductID" datasourceid="ldsProducts" style="margin-top: 20px;"
onpageindexchanging="gvProducts_PageIndexChanging" onrowdatabound="gvProducts_RowDataBound">
    <columns>
        <asp:templatefield headertext="Select">
            <itemtemplate>
                    <asp:checkbox id="chkSelect" runat="server" />
            </itemtemplate>
        </asp:templatefield>
        <asp:boundfield datafield="ProductID" headertext="ProductID" insertvisible="False">
readonly="True" sortexpression="ProductID" />
        <asp:boundfield datafield="ProductName" headertext="ProductName" sortexpression="ProductName" />
    </asp:boundfield></columns>
</asp:gridview>
<asp:linqdatasource id="ldsProducts" runat="server" contexttypename="LinqToSql.NorthwindDataContext" xmlns:asp="#unknown">
tablename="Products">
</asp:linqdatasource>


Code Behind:
C#
public partial class GridView_MaintainCheckBoxStateWhenPaging : System.Web.UI.Page
{
        private List<int> ProductIDs
        {
                get
                {
                        if (this.ViewState["ProductIDs"] == null)
                        {
                                this.ViewState["ProductIDs"] = new List<int>();
                        }

                        return this.ViewState["ProductIDs"] as List<int>;
                }
        }

        protected void SelectDeselect(object sender, CommandEventArgs e)
        {
                foreach (GridViewRow gvr in gvProducts.Rows)
                {
                        CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;

                        if (chkSelect != null)
                        {
                                chkSelect.Checked = e.CommandName.Equals("SelectAll");
                        }
                }
        }

        protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            foreach (GridViewRow gvr in gvProducts.Rows)
            {
                CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
                if (chkSelect != null)
                {
                    int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);

                    if (chkSelect.Checked && !this.ProductIDs.Contains(productID))
                    {
                        this.ProductIDs.Add(productID);
                    }
                    else if (!chkSelect.Checked && this.ProductIDs.Contains(productID))
                    {
                        this.ProductIDs.Remove(productID);
                    }
                }
            }
        }

        protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow gvr = e.Row;

            if (gvr.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
                if (chkSelect != null)
                {
                    int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);
                    chkSelect.Checked = this.ProductIDs.Contains(productID);
                }
            }
        }
}


All the best.

--Amit
 
Share this answer
 
v2
Comments
Taresh Uppal 25-Jul-12 2:35am    
can u please tell me whats wrong in my code that I used ...
_Amy 25-Jul-12 2:40am    
Something you might missed in your code. Don't be in so hurry. Try downloading the source code from the article and try to understand it. That is the only solution I can give you..
Taresh Uppal 25-Jul-12 2:45am    
Amit sir, actually this is the only thing left in my project and I am struggling on it since two days and somehow it always happen that i get some unusual error... The deadline is on the top now....:(
_Amy 25-Jul-12 2:50am    
Put a breakpoint and try debugging your code. Go through each step and trace the error. This is only way to find your error. See where you are loosing your data.

All the best dude. You can do it. Come on..
Taresh Uppal 25-Jul-12 6:03am    
Sir, I again made some changes and now the thing is on button click event I have to send mails to all the clients in my gridview except those on whom check box is checked. For this I am trying traversing my gv through foreach but my foreach is not working at all. It is not able to count the rows and traverse a single row.. y so ?
C#
protected void btn_daily_send_all_Click(object sender, EventArgs e)
    {
        int flag = 0;
        gvAllClients.Visible = true;
        gvAllClients.AllowPaging = false; // this is where is disabled paging
        
        try
        {
            if ((txt_daily_from.Text != "") || (txt_daily_to.Text != ""))
            {
                
                string strSucessEmail = "";
                string strFailedEmail = "";

/* this is my some logic of checking date validations*/
                DateTime date_from_for_daily_email = Convert.ToDateTime(txt_daily_from.Text);
                DateTime date_to_for_daily_email = Convert.ToDateTime(txt_daily_to.Text);
                DateTime date_end = Convert.ToDateTime(ViewState["latest_date_port_uploaded"]);
                DateTime dt = Convert.ToDateTime(ViewState["date_last_mailed"]);
                DateTime date_start = choosing_first_date(ref dt);

              //here i traversed my gv

                foreach(GridViewRow row in gvAllClients.Rows)
                {


                    string strworkOrder = ((Label)(row.Cells[5].FindControl("lblWorkOrd"))).Text;
                    string strdata = ((Label)(row.Cells[6].FindControl("lblData"))).Text;
                    string strHSCODE = ((Label)(row.Cells[9].FindControl("lblHSCode"))).Text;
                    string strCombination = ((Label)(row.Cells[10].FindControl("lblComb"))).Text;
                    string strProd = ((Label)(row.Cells[11].FindControl("lblProd"))).Text;
                    string strProd_Not = ((Label)(row.Cells[12].FindControl("lblProd_not"))).Text;
                    string strActive = ((Label)(row.Cells[13].FindControl("lblActive"))).Text;
                    string strEmailId = ((Label)(row.Cells[14].FindControl("lblEmail"))).Text;
                    DateTime date_from_subscp = Convert.ToDateTime(((Label)(row.Cells[7].FindControl("lblfrom"))).Text);
                    DateTime date_to_subscp = Convert.ToDateTime(((Label)(row.Cells[8].FindControl("lblTo"))).Text);
                    CheckBox chk = (CheckBox)(row.Cells[30].FindControl("chkEmail_Single"));

                    if (strActive == "NO")
                    {
                        strFailedEmail += "" + strEmailId + ", ";
                    }


                    else if (strActive == "YES")   
                    {
                        //((date_from_for_daily_email < date_start) || 
                        if (date_to_for_daily_email > date_end)
                        {
                            lblMsg.Visible = true;
                            lblMsg.Text = "You cannnot select a date less than last mailed date and greater than " + date_end.ToString("dd-MMM-yyyy") + ".";
                        }
                        else if (date_from_for_daily_email > date_to_for_daily_email)
                        {
                            lblMsg.Visible = true;
                            lblMsg.Text = "Invalid date range. Please check the dates and than try again...";
                        }

                        else if (date_to_subscp < date_to_for_daily_email)
                        {
 // this is some of my logic to store the records of success and unsuccessful mails
                            strFailedEmail += "" + strEmailId + ", ";

                        }
                        else if (chk.Checked == true)
                        {
                            strFailedEmail += "" + strEmailId + ", ";
                        }

                        else
                        {
                            int iResult = bl_Query_for_admin.Query_Data_Email_Attachment(strworkOrder, strdata, date_from_for_daily_email, date_to_for_daily_email, strHSCODE, strCombination, strProd, strProd_Not, strEmailId);

                            if (iResult == 1)
                            {
                                if (flag == 0)
                                {
                                    bl_myAccount.insert_last_daily_email_date(date_to_for_daily_email);

                                    flag = 1;
                                }

                                strSucessEmail += "" + strEmailId + ", ";

                                lblMsg.Visible = true;

                                lblMsg.Text = "Email Sent Succesfully !!!";
                                continue;

                            }
                            else
                            {
                                continue;
                            }
                        }


                    }

                }

                btnLog.Visible = true;
                gvAllClients.Visible = true;
                inserting_mail_history(ref strSucessEmail, ref strFailedEmail);


            }
            else
            {
                lblMsg.Visible = true;
                lblMsg.Text = "Please enter a valid date for data mining...";
            }
        }
        catch (Exception ex)
        {

        }
    }



I have binded my gv outside the postback ryt now Sir...
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900