title: ASP.NET grid in 2.0 having trouble with paging to retain value of check box on save button click
body: <p>this is my button click code which fills the grid view</p>
  
  <pre><code>protected void Btnok_Click(object sender, EventArgs e)
      {
  
          try
          {
              if (Page.IsValid)
              {
                  int passoutYear = Convert.ToInt32(passout.SelectedValue);
                  int courseList = Convert.ToInt32(course.SelectedValue);
                  StringBuilder sb = new StringBuilder();
                  string sep = "";
  
  
  
  
                  foreach (ListItem li in Branch.Items)
                  {
                      if (li.Selected)
                      {
                          sb.Append(sep + li.Value);
                          sep = ",";
                      }
                  }
  
                  DataTable dt = placedStudentManager.GetPlacedStudentList(sb, passoutYear, courseList);
                  if (dt != null &amp;&amp; dt.Rows.Count != 0)
                  {
                      GridView1.DataSource = dt;
                      GridView1.DataBind();
                      GridView1.Visible = true;
                      Btnsave.Visible = true;
                      ViewState["dt"] = dt;
                  }
                  else 
                  {
                      noRecordExistOnOkButton.Text = "No Record Exist To Be Inserted For Recruited Students";
                      Btnsave.Visible = false;
                      GridView1.Visible = false;
                  }
              }
          }
          catch (Exception ex)
          {
              COMMON.logger.Error("Error On Button Btnok_Click:CompanySelected.aspx.cs ", ex);
          }
      }
  </code></pre>
  
  <p>this is my button save which save the checked check box gridRow in data base</p>
  
  <pre><code> protected void Btnsave_Click(object sender, EventArgs e)
      {
  
          try
          {
              if (Page.IsValid)
              {
                  int passoutYear = Convert.ToInt32(passout.SelectedValue);
                  int companyId = Convert.ToInt32(company.SelectedValue);
                  int courseId = Convert.ToInt32(course.SelectedValue);
                  string package = txtpackage.Text.Trim();
                  string venu = txtvenue.Text.Trim();
  
                  DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
                  dateInfo.ShortDatePattern = "dd/MM/yyyy";
                  DateTime date = Convert.ToDateTime(vistDate.Text.Trim(), dateInfo);
  
                  DataTable gridviewTbl = new DataTable();
                  DataColumn dc1 = new DataColumn("company_id");
                  DataColumn dc2 = new DataColumn("course_id");
                  DataColumn dc3 = new DataColumn("branch_id");
                  DataColumn dc4 = new DataColumn("student_enrollment");
                  DataColumn dc5 = new DataColumn("company_visit_date");
                  DataColumn dc6 = new DataColumn("venu");
                  DataColumn dc7 = new DataColumn("package");
                  DataColumn dc8 = new DataColumn("passout_year");
                  gridviewTbl.Columns.Add(dc1);
                  gridviewTbl.Columns.Add(dc2);
                  gridviewTbl.Columns.Add(dc3);
                  gridviewTbl.Columns.Add(dc4);
                  gridviewTbl.Columns.Add(dc5);
                  gridviewTbl.Columns.Add(dc6);
                  gridviewTbl.Columns.Add(dc7);
                  gridviewTbl.Columns.Add(dc8);
  
                  if (GridView1 != null &amp;&amp; GridView1.Rows.Count != 0)
                  {
                      int rowCount = GridView1.Rows.Count;
                      int i = 0;
                      foreach (GridViewRow row in GridView1.Rows)
                      {
  
                          CheckBox cb = (CheckBox)row.FindControl("Chek");
  
                          if (cb != null &amp;&amp; cb.Checked)
                          {
                              string enrollmetNo = GridView1.Rows[i].Cells[1].Text.ToString();
                              int branchId = Convert.ToInt32(GridView1.DataKeys[0].Value);
                              gridviewTbl.Rows.Add(companyId, courseId, branchId, enrollmetNo, date, venu, package, passoutYear);
                          }
                          i++;
                      }
  
                      if (gridviewTbl.Rows.Count != 0)
                      {
                          Boolean b = placedStudentManager.SaveSelectdStudent(gridviewTbl);
                          gridNotExist.Text = "Records Successfully inserted";
                      }
  
                      else
                      {
                          gridNotExist.Text = "Please check the record to be inserted";
                          Btnsave.Visible = true;
                          GridView1.Visible = true;
                      }
                  }
                  else
                  {
                      gridNotExist.Text = "Please Select The Recruited Student, so click the ok button first ";
                  }
  
              }
              else 
              {
                  GridView1.Visible = true;
                  Btnsave.Visible = true;
              }
          }
          catch (Exception ex)
          {
              COMMON.logger.Error("Error On Button Btnsave_Click:CompanySelected.aspx.cs ", ex);
          }
  
      }
  </code></pre>
  
  <p>now  i am doing paging using following code </p>
  
  <pre><code> protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
      {
  
          GridView1.PageIndex = e.NewPageIndex;
          GridView1.DataSource = (DataTable)ViewState["dt"];
          GridView1.DataBind();
          GridView1.Visible = true;
          Btnsave.Visible = true;
         // StringBuilder str=(StringBuilder)ViewState["chk"];
          //foreach (GridViewRow row in GridView1.Rows) 
          //{ 
  
          //}
  
      }
  </code></pre>
  
  <p>following is the grid view</p>
  
  <pre><code>   &lt;%@ Page Language="C#" MasterPageFile="~/Master Pages/AdminMaster.master" AutoEventWireup="true"
      CodeFile="CompanySelected.aspx.cs" Inherits="Admin_CompanySelected"  Trace="false"  Title="Untitled Page"  EnableEventValidation="false" %&gt;
  
  
  &lt;asp:Content ID="Content1" ContentPlaceHolderID="cph1" runat="Server"&gt;
  
      &lt;script language="javascript" type="text/javascript"&gt;
  
      function BranchCheckBoxCheck(source, args)
      {
        var chkBoxListId=document.getElementById ('&lt;%=Branch.ClientID%&gt;');
        var chkList=chkBoxListId.getElementsByTagName("input");
        for(var i=0;i&lt;chkList.length;i++)
                  {  
                      if(chkList[i].checked)
                      {
                          args.IsValid = true;
                          return;
                      }
                  }
                args.IsValid = false;
      }
  &lt;/script&gt;
  
  &lt;/asp:Content&gt;
  &lt;asp:Content ID="Content2" ContentPlaceHolderID="cphMain" runat="Server"&gt;
      &lt;div border="1"&gt;
          &lt;table id="TABLE1" onclick="return TABLE1_onclick()" align="center"&gt;
              &lt;tr&gt;
                  &lt;td style="height: 24px"&gt;
                      Passout Year*&lt;/td&gt;
                  &lt;td style="height: 24px"&gt;
                      &lt;asp:DropDownList ID="passout" runat="server"&gt;
                      &lt;/asp:DropDownList&gt;
                      &lt;asp:CustomValidator ID="validateYearForSaveButton" runat="server" ControlToValidate="passout"
                          ErrorMessage="insert passout year" OnServerValidate="validateYearForSaveButton_ServerValidate"
                          ValidationGroup="save"&gt;&lt;/asp:CustomValidator&gt;&lt;/td&gt;
                  &lt;td style="height: 24px"&gt;
                  &lt;asp:CustomValidator ID="passoutYearRequire" runat="server" ErrorMessage="Passout Year is Compulsory" ControlToValidate="passout" ValidationGroup="verify" OnServerValidate="passoutYearRequire_ServerValidate"&gt;
                  &lt;/asp:CustomValidator&gt;
                  &lt;/td&gt;
                  &lt;td style="width: 101px; height: 24px;"&gt;
                  &lt;/td&gt;
                  &lt;td style="width: 126px; height: 24px"&gt;
                  &lt;/td&gt;
                  &lt;td style="height: 24px"&gt;
                  &lt;/td&gt;
                  &lt;td style="height: 24px"&gt;
                  &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;
                      Company Name*&lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:DropDownList ID="company" runat="server"&gt;
                      &lt;/asp:DropDownList&gt;
                      &lt;/td&gt;
                  &lt;td&gt;
                      &amp;nbsp;&lt;asp:CustomValidator ID="selectComapnyForSaveButton" runat="server" ControlToValidate="company"
                          ErrorMessage="Select A Company" OnServerValidate="selectComapnyForSaveButton_ServerValidate"
                          ValidationGroup="save"&gt;&lt;/asp:CustomValidator&gt;&lt;/td&gt;
                  &lt;td style="width: 101px"&gt;
                      Package*&lt;/td&gt;
                  &lt;td style="width: 126px"&gt;
                      &lt;asp:TextBox ID="txtpackage" runat="server" Width="197px"&gt;&lt;/asp:TextBox&gt;&lt;/td&gt;
  
                  &lt;td&gt;
                  &lt;asp:RequiredFieldValidator ControlToValidate="txtpackage" ValidationGroup="save" ID="packageRequire" runat="server" ErrorMessage="Package Require"&gt;&lt;/asp:RequiredFieldValidator&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:Button ID="Btnok" runat="server" Text="Ok" Width="43px" OnClick="Btnok_Click" ValidationGroup="verify" /&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;
                      Course*&lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:UpdatePanel id="update" runat="server"&gt;
                          &lt;contenttemplate&gt;
                          &lt;asp:DropDownList ID="course" runat="server" AutoPostBack="True" OnSelectedIndexChanged="course_SelectedIndexChanged"&gt;
                          &lt;/asp:DropDownList&gt;
                           &lt;/contenttemplate&gt;
                      &lt;/asp:UpdatePanel&gt;&lt;asp:CustomValidator ID="coursenecessaryForSaveButton" runat="server"
                          ControlToValidate="course" ErrorMessage="Select A Course" OnServerValidate="coursenecessaryForSaveButton_ServerValidate"
                          ValidationGroup="save"&gt;&lt;/asp:CustomValidator&gt;&lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:CustomValidator ID="courseNecessary" runat="server" ErrorMessage="Select A Course"
                          OnServerValidate="courseNecessary_ServerValidate" ValidationGroup="verify"&gt;&lt;/asp:CustomValidator&gt;&lt;/td&gt;
                  &lt;td style="width: 101px"&gt;
                      Branch Name*&lt;/td&gt;
                  &lt;td style="width: 126px"&gt;
                      &lt;asp:UpdatePanel id="upchak" runat="server"&gt;
                          &lt;contenttemplate&gt;
  &lt;asp:CheckBoxList id="Branch" runat="server" OnSelectedIndexChanged="Branch_SelectedIndexChanged"&gt;
                      &lt;/asp:CheckBoxList&gt; 
  &lt;/contenttemplate&gt;
                      &lt;/asp:UpdatePanel&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                  &lt;asp:CustomValidator id="branchRequire" runat="server" ValidationGroup="verify" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"&gt;&lt;/asp:CustomValidator&gt;
                 &lt;asp:CustomValidator id="branchrequireForSaveButton" runat="server" ValidationGroup="save" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"&gt;&lt;/asp:CustomValidator&gt;
                &lt;%-- &lt;asp:CustomValidator ID="branchNotexist" runat="server" ErrorMessage="No Branch Exist" ValidationGroup="verify"  ControlToValidate="Branch" OnServerValidate="branchNotexist_ServerValidate"&gt;&lt;/asp:CustomValidator&gt;--%&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:Button ValidationGroup="save" ID="Btnsave" runat="server" Text="Save" OnClick="Btnsave_Click" /&gt;
                  &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;
                      Company Visit Date*&lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:TextBox ID="vistDate" runat="server" &gt;&lt;/asp:TextBox&gt;
                      &lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:RequiredFieldValidator ID="dateForSaveButton" runat="server" ControlToValidate="vistDate"
                          ErrorMessage="Visit Date Require" ValidationGroup="save"&gt;&lt;/asp:RequiredFieldValidator&gt;&lt;/td&gt;
                  &lt;td style="width: 101px"&gt;
                  &lt;/td&gt;
                  &lt;td style="width: 126px"&gt;
                      &lt;asp:Label ID="noRecordExistOnOkButton" runat="server" Text="Label" Width="178px"&gt;&lt;/asp:Label&gt;&lt;/td&gt;
                  &lt;td&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                      &amp;nbsp;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;
                      Venue*
                  &lt;/td&gt;
                  &lt;td&gt;
                      &lt;asp:TextBox ID="txtvenue"  runat="server"&gt;&lt;/asp:TextBox&gt;
                  &lt;/td&gt;
                  &lt;td colspan="4"&gt;
                      &lt;asp:RequiredFieldValidator ID="venRequire" runat="server" ControlToValidate="txtvenue"
                          ErrorMessage="Insert venu" ValidationGroup="save" Width="73px"&gt;&lt;/asp:RequiredFieldValidator&gt;
                      &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;
                      &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;
                      &lt;asp:Label ID="gridNotExist" ForeColor="Red" runat="server" Width="439px"&gt;&lt;/asp:Label&gt;&lt;/td&gt;
                  &lt;td&gt;
                      &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td colspan="5" style="height: 16px"&gt;
                  &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td colspan="5"&gt;
  
  
  
  &lt;asp:GridView id="GridView1" AllowSorting="true" EnableViewState="true" AutoGenerateColumns="false" runat="server" AllowPaging="True"  DataKeyNames="branch_id, default_check, student_id"   OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="2"&gt;
  
  &lt;Columns&gt;
  &lt;asp:TemplateField HeaderText="Select Student"&gt;
  &lt;ItemTemplate&gt;
  &lt;asp:CheckBox id="Chek"  runat="server" Text="select" &gt;&lt;/asp:CheckBox&gt;
  &lt;/ItemTemplate&gt;
  &lt;/asp:TemplateField&gt;
  &lt;asp:BoundField HeaderText="Enrollment No." DataField="enrollment_no" /&gt;
  &lt;asp:BoundField HeaderText="Course Name" DataField="course_name"/&gt;
  &lt;asp:BoundField  HeaderText="Branch Name"  DataField="branch_name"/&gt;
  &lt;asp:BoundField HeaderText="Email Id" DataField="email" /&gt;
  &lt;asp:BoundField  HeaderText="Mobile" DataField="mobile"/&gt;
  &lt;asp:BoundField HeaderText="Name"  DataField="first_name"/&gt;
  &lt;asp:BoundField  HeaderText="Surname" DataField="last_name" /&gt;
  &lt;/Columns&gt;
  
  
  &lt;/asp:GridView&gt; 
                  &lt;/td&gt;
              &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
          &lt;/table&gt;
      &lt;/div&gt;
      &lt;br /&gt;
      &lt;br /&gt;
      &lt;br /&gt;
      &lt;br /&gt;
      &amp;nbsp;&amp;nbsp;
      &lt;br /&gt;
      &lt;br /&gt;
      &lt;br /&gt;
  &lt;/asp:Content&gt;
  </code></pre>
  
  <p>now i want to do paging without loosing check box state and want to save the selectd check box row in data base on save button click how to achieve this please let me know .
  I am using dot net framework 2.0...</p>
  
  <p>@PhilPursglove :- My solution is like this</p>
  
  <pre><code>protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) 
  { Response.Write(GridView1.PageIndex.ToString()); 
  int d = GridView1.PageCount; bool[] values = new bool[GridView1.PageSize];
   CheckBox chb; 
  for (int i = 0; i &lt; GridView1.Rows.Count; i++) 
  { 
  chb = (CheckBox)GridView1.Rows[i].FindControl("Chek"); 
  if (chb != null) 
  {
   values[i] = chb.Checked; 
  } 
  }
  Session["page" + GridView1.PageIndex] = values;
  GridView1.PageIndex = e.NewPageIndex; 
  GridView1.DataSource = (DataTable)ViewState["dt"]; 
  GridView1.DataBind(); GridView1.Visible = true; Btnsave.Visible = true; 
  } 
  
  protected void GridView1_PreRender(object sender, EventArgs e) 
  { 
  if (Session["page" + GridView1.PageIndex] != null) 
  { CheckBox chb; bool[] values = (bool[])Session["page" + GridView1.PageIndex]; 
  for (int i = 0; i &lt; GridView1.Rows.Count; i++) 
  { chb = (CheckBox)GridView1.Rows[i].FindControl("Chek"); 
  chb.Checked = values[i]; 
  }
   }
   }
  </code></pre>
  
  <p>now i want on save button to store those selected chkbox row values to database</p>