w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Remove items from ListBox if item exists in another ListBox

Well you're only referencing one list box in your code - I suspect you would want:

private void button1_Click(object sender, EventArgs e) {

foreach (int item in listBox1.Items)
{
    if (listBox2.Items.Contains(item))   // notice change of reference
    {
        listBox1.Items.Remove(item);
    }
}

However that would cause an error since you're modifying the ListBox while you're iterating over it's items. One way to safely remove items it to iterate backwards over the colection:

for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
    int item = listBox1.Items[i];
    if (listBox2.Items.Contains(item))   // notice change of reference
    {
        listBox1.Items.RemoveAt(i);
    }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.