Reputation: 3484
I am trying to remove one row from a datagridview when user selects a row and then clicks the "Delete" button. I am using the following code:
private void btnDel_Click(object sender, EventArgs e) { dgvSearchResults.ReadOnly = false; if (MessageBox.Show("Are you sure?", "confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes) { dgvSearchResults.Rows.RemoveAt(dgvSearchResults.SelectedRows[0].Index); ole_da.Update(dTable); } }
And I am getting the following error when debugging:
{"Update requires a valid DeleteCommand when passed DataRow collection with deleted rows."}
I am pretty new to C# and have no idea how to create a DeleteCommand or use CommandBuilder (as suggested in some SO posts) to solve this problem.
Upvotes: 0
Views: 527
Reputation: 3484
Thanks to @Orkun-Bekar, the following finally solved the problem:
private void btnDel_Click(object sender, EventArgs e) { dgvSearchResults.ReadOnly = false; if (MessageBox.Show("Delete?", "confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes) { dgvSearchResults.Rows.RemoveAt(dgvSearchResults.SelectedRows[0].Index); ole_da.SelectCommand = new OleDbCommand("SELECT * FROM Projects"); ole_da.SelectCommand.Connection = conn; oleCmdBuilder = new OleDbCommandBuilder(ole_da); ole_da.Update(dTable); } }
Where, ole_da is given a select command that selects all items from the table in question. It's then given a connection i.e. conn. Making use of OleDbCommandBuilder class then will automate the deletion of the selected row, without needing for an explicit DeleteCommand to be specified.
Upvotes: 0
Reputation: 1441
In your click event do that:
ole_da.SelectCommand = yourSelectCommand;
OleDbCommandBuilder oleDbCommandBuilder = new OleDbCommandBuilder(ole_da);
ole_da.Update(dTable);
Upvotes: 1