简体   繁体   中英

Deleting selected row from datagridview and database

I am writing this code for deleting selected row from datagridview and database at a time. but i got the error in "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();
                        }
                    }
                }
 }

} 

Wrap rowIdToDelete within quotes.

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

Also if ID is column name with add double quotes,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM