Collection was modified; enumeration operation may not execute : .NET Error

For example, suppose I have a treeview control and a “clear all” button to uncheck all checkboxes. Following is the code on button click event



protected void btnClear_Click(object sender, EventArgs e)
{
foreach (TreeNode node in treeSearch.CheckedNodes)
{
node.Checked = false;
}
}


It throws error “Collection was modified; enumeration operation may not execute” The error is self explanatory, we cannot alter a collection when using an enumerator or else the enumerator becomes invalid. So, I modified foreach loop to for loop. Now it doesn’t give any error but logically wrong. How?


protected void btnClear_Click(object sender, EventArgs e)
{
for (int i = 0; i < treeSearch.CheckedNodes.Count; i++)
{
treeSearch.CheckedNodes[i].Checked = false;
}
}


Suppose I select 4 nodes then it will clear 1 and 3 node only. 2 and 4 are not cleared because loop increments. Actually we need not to increment loop.
So, no need to put i++ Or use following code to do this


protected void btnClear_Click(object sender, EventArgs e)
{
while (treeSearch.CheckedNodes.Count>0)
{
treeSearch.CheckedNodes[0].Checked = false;
}
}

So Be careful, about this logical error.

No comments:

Post a Comment