Datagridview行数据删除查询代码无法正常工作

时间:2019-04-17 13:57:39

标签: c# sql datagridview rowdeleting

我可以从datagridview删除行,但是不能在带有查询代码的sql表中删除行。所以基本上我的“字符串查询”代码给出了一个错误。

https://imgur.com/2fn1RCf https://imgur.com/IMc7gBV

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");
}

1 个答案:

答案 0 :(得分:0)

我删除了'i'变量,并将其更改为0,现在代码运行良好,谢谢帮助

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");