views:

308

answers:

3

I have used a ListBox in my Windows application. I got the variable iplist from a WCF server.

After that i addded that list in my ListBox, but it generated an error: "Collections modified, enumuration may not execute".

How might I solve this problem?

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);
            }
         }
    }
}
+1  A: 

You can't add to an enumeration, in this case your listbox, whilst you are iterating over the collection.

You probably want something like:

using System.Linq;
...

foreach (ClsPC pc in iclsobj.GetPC()) 
{     
    if (listBox1.Items.Count == 0) 
    { 
        listBox1.Items.Add(pc.IPAddress); 
    } 
    else 
    { 
        if (!listBox1.Items.Any(i => String.Compare(i.ToString(), pc.IPAddress, true) == 0))
        {
           listBox1.Items.Add(pc.IPAddress); 
        }
   } 
}
James
if (!listBox1.Items.Any(i => String.Compare(i.ToString(), pc.IPAddress, true) == 0)) {In this line i didnt get Listbox1.Items.Any function option...now how shall i add the values in listbox
Suryakavitha
You need to add a reference to System.Linq and add a using to your code unit. See update example
James
A: 

Your problem is exactly what james says, you can't add to an enumeration while iterating over the collection. Though you could also solve it in this way. (I'm assuming that pc.IPAddress is a string, if they're something else, just switch the type.)

foreach (ClsPC pc in iclsobj.GetPC())
{
    if (listBox1.Items.Count == 0)
    {
         listBox1.Items.Add(pc.IPAddress);
    }
    else
    {
        var toAdd = new List<string>();
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            if (!listBox1.Items[i].ToString().Contains(pc.IPAddress))
            {
                toAdd.Add(pc.IPAddress);
            }
         }
         toAdd.ForEach(item => listBox1.Items.Add(item));
    }
}
wasatz
@wasatz, the question says `without using for loop'
James
Crap! I totally missed that. Alright, in that case my code is completely irrelevant. Sorry about that.
wasatz
A: 

If you read your code it is probably not what you want. You want to add the IP address to the list if it not exists right?

for (int i = 0; i < listBox1.Items.Count; i++)
{
 if (!listBox1.Items[i].ToString().Contains(pc.IPAddress))
 {
  listBox1.Items.Add(pc.IPAddress);
 }
}

What you do now is loop over the items in the listbox. if an item does not contain the ipaddress you will add it to the listbox. What you want is add the ipaddress when it's not occuring the the whole listbox. Therefore:

//IPAddress is a string?
if (!listBox1.Items.Contains(pc.IPAddress))
{
 listBox1.Items.Add(pc.IPAddress);
}
PoweRoy