Reputation: 20001
I have two Listbox in asp.net webform application.
LIstBox1 has List of all Projects & ListBox2 has assigned project.
One page Load both ListBox1 is populated with all Project & ListBox2 is populated with assigned Project & I have a button which removed the Assigned Project from LIstbox2
var itms1 = ListBox1.Items;
var itms2 = ListBox2.Items;
foreach (var itm in itms2)
{
if (itms1.Contains(itm)) itms1.Items.Remove(itm);
}
I get error error on this as shown in image:
I simply want to compare ListBox2 with ListBox1 and remove matching ListBox2 values from ListBox1.
I tried different varies but I keep getting similar error or it won't work.
ListBox show ProjectName as Text and ProjectID as Listbox Values
I am using asp.net webform application on .net framework 4.5
Upvotes: 0
Views: 317
Reputation: 20001
This is what worked for me
foreach (ListItem itemA in LisyBox2.Items)
{
for (int i = ListBox1.Items.Count - 1; i > -1; i--)
{
{
if (ListBox1.Items[i].Text == itemA.Text)
{
ListBox1.Items.RemoveAt(i);
}
}
}
}
Upvotes: 0
Reputation: 108
You can simply use this:
itms1.RemoveAll( item => itms2.Contains(item));
This code removes all items that are in list2
Upvotes: 0