0

I am having issue with my gridview

  1. It is giving me error while moving from one page to another
  2. It is not retaining checkbox state on paging

Getting error on KeepChecks

ERROR MESSAGE Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index ERROR MESSAGE

Below is the code...

Your help and assistance will be appriciated

 public partial class AdminConsole : System.Web.UI.Page
{

    SqlDataAdapter da;
    DataSet ds = new DataSet();


    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            BindData();
        }

    }





    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

    }

    private void BindData()
    {
        SqlCommand cmd = new SqlCommand("SELECT UserID, EmployeeID, UserName, Dept FROM vw_UserID_Dept", con);

        try
        {
            da = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();
            da.Fill(ds);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            //GVRegisterNewCarton.DataSource = ds;
            //GVRegisterNewCarton.DataBind();

         if (!object.Equals(ds.Tables[0], null))
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                GVRegisterNewCarton.DataSource = ds.Tables[0];
                GVRegisterNewCarton.DataBind();
                Session["MyTable"] = ds.Tables[0];
            }
            else
            {
                GVRegisterNewCarton.DataSource = null;
                GVRegisterNewCarton.DataBind();
            }
        }
        else
        {
            GVRegisterNewCarton.DataSource = null;
            GVRegisterNewCarton.DataBind();
        }
    }
    catch (Exception ex)
    {

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
        lblStatus.Text = ex.Message;

    }




    }

    protected void GVRegisterNewCarton_PageChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            KeepChecks();
            GVRegisterNewCarton.PageIndex = e.NewPageIndex;
            BindData();
            ApplyChecks();
        }

        catch (Exception ex)
        {

            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
            lblStatus.Text = ex.Message;

        }

    }




    private void KeepChecks()
{
    try
    {
        ArrayList chkList = new ArrayList();
        int index = -1;
        foreach (GridViewRow gvrow in GVRegisterNewCarton.Rows)
        {
            index = (int)GVRegisterNewCarton.DataKeys[gvrow.RowIndex].Value;
            bool result = ((CheckBox)gvrow.FindControl("chkSelectAdd")).Checked;

            if (Session["RemindChecks"] != null)
                chkList = (ArrayList)Session["RemindChecks"];
            if (result)
            {
                if (!chkList.Contains(index))
                    chkList.Add(index);
            }
            else
                chkList.Remove(index);
        }
        if (chkList != null && chkList.Count > 0)
            Session["RemindChecks"] = chkList;
    }
    catch (Exception ex)
    {

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
        lblStatus.Text = ex.Message;

    }
}


private void ApplyChecks()
{
    try
    {
        ArrayList chkList = (ArrayList)Session["RemindChecks"];
        if (chkList != null && chkList.Count > 0)
        {
            foreach (GridViewRow gvrow in GVRegisterNewCarton.Rows)
            {
                int index = (int)GVRegisterNewCarton.DataKeys[gvrow.RowIndex].Value;
                if (chkList.Contains(index))
                {
                    CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelectAdd");
                    myCheckBox.Checked = true;
                }
            }
        }
    }

    catch (Exception ex)
    {

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Error Binding Grid');", true);
        lblStatus.Text = ex.Message;

    }
}
Aditya
  • 73
  • 9

1 Answers1

0

Found a simpler alternate solution to the issue

protected void GVRegisterNewCarton_PageChanging(object sender, GridViewPageEventArgs e)
{

    string pageId = string.Format("Page{0}", GVRegisterNewCarton.PageIndex);
    bool[] selectedCheckboxes = new bool[GVRegisterNewCarton.PageSize];
    for (int i = 0; i < GVRegisterNewCarton.Rows.Count; i++)
    {
        TableCell cell = GVRegisterNewCarton.Rows[i].Cells[0]; 
        selectedCheckboxes[i] = (cell.FindControl("chkSelectAdd") as CheckBox).Checked; 
    } 
    ViewState[pageId] = selectedCheckboxes;
    GVRegisterNewCarton.PageIndex = e.NewPageIndex;
    BindData();
    //Bind the gridview again 


}


protected void GVRegisterNewCarton_PreRender(object sender, EventArgs e) 

{ string pageId = string.Format("Page{0}",
    GVRegisterNewCarton.PageIndex); 
    bool[] selectedCheckboxes = ViewState[pageId] as bool[]; 
    if (selectedCheckboxes != null) { for (int i = 0;
        i < GVRegisterNewCarton.Rows.Count; i++) 
        {
            TableCell cell = GVRegisterNewCarton.Rows[i].Cells[0]; 
        (cell.FindControl("chkSelectAdd") as CheckBox).Checked = selectedCheckboxes[i]; 
    } 
    } 
}
Masoud Mohammadi
  • 1,721
  • 1
  • 23
  • 41
Aditya
  • 73
  • 9