Search code examples
c#winformsdatagridviewdelete-row

Delete any row from DataGridView as well as from database


I want to delete the selected row from DataGridView as well as the database. My code works only for the first row, for every other row it gives exception "Index was out of Range".

        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand();
        string itemId;
        if (dgPartyDetails.SelectedCells.Count > 0)
        {
            int selectedrowindex = dgPartyDetails.SelectedCells[0].RowIndex;
            try
            {
                DataGridViewRow selectedRow = dgPartyDetails.SelectedRows[selectedrowindex];
                if (selectedRow.Selected == true)
                {
                    dgPartyDetails.Rows.RemoveAt(selectedrowindex);
                    itemId = Convert.ToString(selectedRow.Cells[0].Value);
                    con.Open();
                    cmd.CommandText = "DELETE FROM tblParty WHERE Id=" + itemId + "";
                    cmd.Connection = con;
                    int count = cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }       

Solution

  • It appears that you removed the DataGridRow before obtaining it's value.

    dgPartyDetails.Rows.RemoveAt(selectedrowindex);
    itemId = Convert.ToString(selectedRow.Cells[0].Value);
    

    Reversing the order of these statement would fix your problem.

    itemId = Convert.ToString(selectedRow.Cells[0].Value);
    dgPartyDetails.Rows.RemoveAt(selectedrowindex);