0

I have a GridView within a LoginView that I am running into this issue when I click the edit button. I know that I need to use FindControl to get to the objects within the LoginView so I have done that. But now I am having this IndexOutOfRangeException error. I posted the index and the DataKeys.Count to an error label and I don't see the issue. But it comes up in the xx.Rows[e.RowIndex] only. If I only use e.RowIndex (for example: int index = e.RowIndex.ToString();) I won't get the same error. So I have it narrowed down to that but cannot figure it out from here. If you need for me to post any other parts of the code please let me know.

The line giving me fits is the GridViewRow row = gv.Rows[e.RowIndex]; line.

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
    if (gv.DataKeys.Count > e.RowIndex)
    {
        GridViewRow row = gv.Rows[e.RowIndex];

        string Id = (row.FindControl("lblID") as Label).Text;

        string constr = System.Configuration.ConfigurationManager.AppSettings["DefaultConnection"];
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("cardReview"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@id", Id);

                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        gv.EditIndex = -1;
        this.BindGrid();
    }
}
b3ns
  • 25
  • 9
  • Are you using paging? – Jeroen van Langen Aug 12 '16 at 14:45
  • I'm not using paging. I have tried to look at the other answers on here but none of them have fixed my issue. Are there any known quirks about using GridViews within LoginViews? – b3ns Aug 12 '16 at 14:48
  • What if you use `gv.Rows.Count` instead of `gv.DataKeys.Count`. It looks like there is a difference between them. – Jeroen van Langen Aug 12 '16 at 14:52
  • Changing to gv.Rows.Count will make the code at least not fire. It is as if the gv.Rows[e.RowIndex] is returning a -1 for some reason but I cannot figure out why. – b3ns Aug 12 '16 at 14:55
  • Just had the gv.Rows.Count display in an error label and it is always 0. So the GridView is not getting the correct number of rows for some reason. – b3ns Aug 12 '16 at 15:01
  • 1
    You should convert this line `GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;` to `GridView gv = sender as GridView;` – bastos.sergio Aug 12 '16 at 15:44

0 Answers0