How to delete multiple rows in a DataGridView
I am trying to delete multiple selected rows from a DataGridView. Wh开发者_如何学Goen 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 quite hard to read. Anyway I'm sure the problem is in the foreach
. In general you can't delete item within the foreach loop from the collection it is looping on.
anyway I think the best choice would be remove the item from the datasource(maybe getting the id's from the repeater) and DataBind the repeater again
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 BindingSource
object. It makes table management much easier. Set the datasource of the BindingSource
to the table and the datasource of the DataGridView
to the BindingSource
object, and any changes made to the table will be reflected in the DataContext
after calling SubmitChanges()
.
Example:
MyDataContext dataContext = new MyDataContext();
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = dataContext.MyTable;
dataContext.DataSource = bindingSource;
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.
I agree with @Massimiliano Peluso; in general, I would get all ids in one shot and make just one Database call passing a comma-separated list of ids to be deleted instead of calling one per row, unless of course, there are some other valid reasons for not doing it that way but calling the DB 200 times when you can call it once and be done seems unnecessary to me. I would then rebind the data and be done with it.
精彩评论