从datagridview和数据库中删除选定的行

时间:2013-12-22 05:23:09

标签: c# winforms datagridview

我正在编写此代码,一次从datagridview和数据库中删除所选行。 但我在“deleteButton.Click”中得到了错误

deleteButton.Click += new System.EventHandler(this.DeleteRecord);

 private DeleteRecord(object sender, EventArgs e)
{


foreach(DataGridViewRow row in DataGridView1.SelectedRows)
 {
  int rowIdToDelete = row.Cells[ID].Value;
  using (OleDbConnection conn = new OleDbConnection(connectionString))
                {
                    string query = "DELETE FROM [Record] WHERE ID = " + rowIdToDelete;
                    conn.Open();

                    using (OleDbCommand cmd = new OleDbCommand(query, conn))
                    {
                        using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
                        {
                            DataTable ds = new DataTable();
                            adapter.Update(ds);
                            dataGridView.DataSource = ds;
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
 }

} 

1 个答案:

答案 0 :(得分:0)

在引号内包裹rowIdToDelete

string query = "DELETE FROM [Record] WHERE ID = " + "'rowIdToDelete'";

如果ID是包含添加双引号的列名,

int rowIdToDelete = row.Cells["ID"].Value;