I am trying to delete multiple selected rows from a DataGridView. When I try the code below, it will only delete just a few of the selected rows. An example, I have seven rows, I select 5 consecutive rows and press delete and only three get deleted.
IEnumerable<DataGridViewRow> dgvrs = from dgvrws in dgvChemicalInv.Rows.Cast<DataGridViewRow>()
where dgvrws.Selected.Equals(true)
select dgvrws;
foreach ( DataGridViewRow dgr in dgvrs )
{
dctchemri = dgr.Cells["DCT_CHEMRI"].Value.ToString();
index = dgvChemicalInv.CurrentRow.Index;
var chemObj = ( from chmObj in DCTProjectNodeObj.Chemicals
where chmObj.DCTChemRI.Equals(dctchemri)
select chmObj ).Single();
if ( sqlCmd.Delete_Chems(this.projID, (csDCTChemicalObj)chemObj) )
{
dgvChemicalInv.Rows.Remove(dgr);
}
if ( dgvChemicalInv.RowCount > 0 )
{
DCTProjectNodeObj.Chemicals.Remove((csDCTChemicalObj)chemObj);
}
else
{
DCTProjectNodeObj.Chemicals = new List<csDCTChemicalObj>();
DO_BtnSaveClickEvent();
}
}
Thank you,
Bill O.
Your code is a little difficult to read, but I think that you are making this too complicated. I would recommend using something like a
BindingSourceobject. It makes table management much easier. Set the datasource of theBindingSourceto the table and the datasource of theDataGridViewto theBindingSourceobject, and any changes made to the table will be reflected in theDataContextafter callingSubmitChanges().Example:
It’s been a while since I’ve done this, but I think this is the easiest way to do it. This avoids any messy operations, however it can lead to complications with foreign key relationships.
Just a way that might make things simpler.