简体   繁体   中英

DataTable Deleted Rows Issues

I have an app that we maintain that is years old. Suddenly, rows deleted in a DataTable are showing up in the DataTable. They are marked as deleted, but they show up in the Row.Count, and if I try to loop through the table rows, I get Cannot access deleted rows errors. If I do an AcceptChanges() , the deleted records do disappear.

For example this line of code, where I had previously deleted all the rows, would error out with the cannot access error:

foreach (DataRow rwUpdatedRefs in tblUpdatedRefs.Rows)

Does anyone have an idea why this would deleted records would start showing up? Is there some setting I may have accidently set?

A deleted DataRow doesn't disappear from the rows collection of a DataTable until you call AcceptChanges. It has always worked in this way. If you loop over a collection of rows where thera are deleted rows you will get the exception mentioned in your question. There is no settings to 'hide' those rows.

However, if you still want to loop over the rows collection without calling AcceptChanges on the DataTable you could still execute the loop excluding the Deleted Rows with:

foreach(DataRow rwUpdatedRefs in tblUpdatedRefs.Rows.Cast<DataRow>()
                                 .Where(r => r.RowState != DataRowState.Deleted))

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