Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello,

I want to know how to clear items from listbox2 which will then erase items from listbox1 as well. Similar items, that is.

What I have tried:

C#
if (listBox2.Items == listBox1.Items)
            {
                listBox1.Items.Clear();

            }

This code is totally wrong, but I want to fix it.
Posted
Updated 28-Jan-22 8:35am
v2
Comments
Richard MacCutchan 27-Jan-22 12:33pm    
You need to create a loop through listbox2 and as you delete each item you need to see if it is also in listbox1.

You can't change two dependent ListBox through loop on runtime because an enumerator is associated with List on traversing and It can only be used if the list does not change. You can achieve this with third container. First you have you find out matched items and then remove from lists. Like below code:

List<object> toRemove = new List<object>();
foreach (string item1 in listBox1.Items)
{
     foreach (string item2 in listBox2.Items)
     {
             if (item1.Contains(item2))
             {
                    toRemove.Add(item2);                        
                    break;
             }
     }
}
if (toRemove.Count > 0)
{
     foreach (var item in toRemove)
     {
            listBox1.Items.Remove(item);
            listBox2.Items.Remove(item);
     }
}
 
Share this answer
 
Try something like this.
C#
var listBox1 = new ListBox();
var listBox2 = new ListBox();
for (int i = 0; i < listBox1.Items.Count; i++)
{
    int index = listBox2.Items.IndexOf(listBox1.Items[i]);
    if (index != -1)
    {
        listBox2.Items.RemoveAt(index);
    }
}
You can't use foreach with list boxes, so use for.

IndexOf finds the item in the second list box. Items start at 0, and -1 means the item was not found. You could also instead use Items.Contains to see if the item is in the second list box.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900