Search code examples
c#sqldatagridviewrowdeleting

Datagridview row data deletion Query code doesnt work correctly


I can able to delete rows from datagridview but cant in sql tables with query code. So basically my 'string query ' code gives an error.

https://i.sstatic.net/btrYT.jpg https://i.sstatic.net/aezx8.jpg

private void removebtn_Click(object sender, EventArgs e)
{
     connection.Open();
     int i;
     i = dataGridView1.SelectedCells[0].RowIndex;
     string query = "DELETE FROM PatientRecords WHERE Id=" + dataGridView1.SelectedRows[i].Cells[0].Value.ToString() + "";
     SqlCommand delcmd = new SqlCommand(query, connection);
     delcmd.ExecuteNonQuery();

     dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index);
     MessageBox.Show("Selected Save Deleted");
}

Solution

  • I deleted ' i ' variable , and change them with 0 now code working well thanks for helps

    string query = "DELETE FROM PatientRecords WHERE Id=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
            SqlCommand delcmd = new SqlCommand(query, connection);
            delcmd.ExecuteNonQuery();
    
            dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
            MessageBox.Show("Selected Save Deleted");