Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET ADO.NET
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 24-Jul-12 20:50pm
Edited 24-Jul-12 21:14pm
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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: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:
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
  Permalink  
v2
Comments
Taresh Uppal at 25-Jul-12 2:35am
   
can u please tell me whats wrong in my code that I used ...
_Amy at 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 at 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 at 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 at 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 ?
_Amy at 25-Jul-12 6:11am
   
Follow the steps:
1) Store your grid data source ie. datatable to session.
2) Add another column called "Check"(Type Bool) in the datatable stored in session.
3) Whenever you are checking the checkbox, update the value of the session datatable(While paging also), and rebind the grid with the session datatable again.
 
Finally on click of any Button:
Iterate through the datatable which is stored in session. And find the unchecked data and do the manipulation based the column "Check".
Taresh Uppal at 25-Jul-12 6:36am
   
err...What I did...I binded my data outside if(!ispostback) and it solved the issue but the grid view is getting traversed only on the first page. And I have paging upto 30 pages. Even I made allow paging to false, still...what shall I do now ?
_Amy at 25-Jul-12 6:43am
   
This is not a good practice. You just post your code here. I'll try to modify it..
Taresh Uppal at 27-Jul-12 8:00am
   
I did it bit following your advice, bit using my mind.. bit with my luck..Thanx a lot sir,,:)
_Amy at 27-Jul-12 8:02am
   
Always welcome Taresh.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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...
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 350
1 Jochen Arndt 190
2 Richard MacCutchan 135
3 Sergey Alexandrovich Kryukov 130
4 DamithSL 105
0 OriginalGriff 6,045
1 DamithSL 4,601
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,310


Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 25 Jul 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100