We cannot use the following code, we may get the following error:
"Collection was modified; enumeration operation may not execute."
using (SPSite site = new SPSite("http://server")) {
using (SPWeb web = siteCollection.OpenWeb()) {
SPList list = web.Lists["MyList"];
foreach (SPListItem item in list.Items) {
item.Delete();
}
}
}
We also cannot use the following code:
for (int i = 0; i < list.Items.Count; i++) {
list.Items.Delete(i);
}
The correct code is as follows:
The correct method for deleting list items is to use a decrementing For loop.
for (int i = list.Items.Count - 1; i >= 0; i--) {
list.Items.Delete(i);
}
For details refer the following link.
No comments:
Post a Comment