0

I am trying to delete a row in a database through a grid view, however, I am receiving this error: "Index was out of range. Must be non-negative and less than the size of the collection."

 protected void ClientDataGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
 {
    String strConnString = ConfigurationManager.ConnectionStrings["PADSConnectionString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);    
    string client_code = ClientDataGrid.DataKeys[e.RowIndex].Values["client_code"].ToString();
    con.Open();
    SqlCommand cmd = new SqlCommand("delete from client where client_code=" + client_code, con);
    int result = cmd.ExecuteNonQuery();
    con.Close();
    if (result == 1)
    {
        ClientDataGrid.DataBind();
        Label1.Text = "Deleted successfully";
    }
}

protected void ClientDataGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{       
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string client_code = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "client_code"));
        Button lnkbtnresult = (Button)e.Row.FindControl("ButtonDelete");
        if (lnkbtnresult != null)
        {
            lnkbtnresult.Attributes.Add("onclick", "javascript:return deleteConfirm('" + client_code + "')");
        }
    }

}

Specifically getting the error on this line

    string client_code = 
    ClientDataGrid.DataKeys[e.RowIndex].Values["client_code"].ToString();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939

0 Answers0