有我的工作解決方案。 首先刪除數據庫中的行,然後重新填充datagridview。 注意:我使用數據庫訪問(oledbcommand,oledbconnection等),更改您的連接。
try
{
//connectDB is the procedure to connect to database:
connectDB();
//this delete first the selected rows in database, and then update datagrid
int countRows = dataGridView1.SelectedRows.Count;
for (int i = 0; i < countRows; i++)
{
int currentRow = dataGridView1.SelectedRows[0].Index;
//con.oledbcon is the conecction is the OleDbConnection procedure, miTable = name of your table
OleDbCommand com = new OleDbCommand("DELETE FROM miTable WHERE Id=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString(), con.oledbcon);
// delete from database
com.ExecuteNonQuery();
// THIS IS THE KEY!!! deselect the last row selected to be able to delete the next row in the next loop
dataGridView1.Rows[currentRow].Selected = false;
}
// all OK
MessageBox.Show("Rows deleted!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
//in case of error
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
//disconnectDB is the procedure to disconnect to database:
disconnectDB();
// and finally, refill datagrid again
loaddatagrid();
}
你在'Virtual'模式下使用'DataGridView'嗎?你如何將數據綁定到網格? – Junaith
你的gridview有數據源嗎?爲什麼不刪除你想從它的數據源獲得的所有記錄,然後你可以調用gridview.databind()刷新UI,這樣你就不需要手動刪除gridview行。 – NomNomNom
我沒有綁定gridview。我正在調用form.GridTestReport.Rows.Add()。我沒有使用虛擬模式。 –