I am using WCf service in my windowsApplication… I got the exception in my client When i am trying to add items in Listbox by using ForEach Loop… The exception is “Collection was modified enumuration may not execute”.
How shall i solve this exception….
And my code is,
foreach (ClsPC pc in iclsobj.GetPC())
{
if (listBox1.Items.Count == 0)
{
listBox1.Items.Add(pc.IPAddress);
}
else
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (!listBox1.Items[i].ToString().Contains(pc.IPAddress))
{
listBox1.Items.Add(pc.IPAddress);
}
}
}
}
client.Close();
client = null;
}
You’re trying to modify the collection in you list box while looping through it (the inner loop), which isn’t really such a hot idea. You’d be better performing this in your data select (i.e. a get distinct PC), or limiting the returned list, possibly something like:
And then just binding your listbox to this.