Reputation: 1064
I want to remove all tab items when i click the logout button My code is given below
foreach (object item in mainTab.Items)
{
TabItem ti = (TabItem)item;
if ("welcomeTabItem" != ti.Name)
{
mainTab.Items.Remove(item);
}
}
But this will create a following error
error-Collection was modified; enumeration operation may not execute.
Is any other method is existing?
Upvotes: 2
Views: 3308
Reputation: 32481
You cannot edit IEnumerables
in foreach
loops. insted use a for
loop.
for (int i = mainTab.Items.Count -1; i >=0; i--)
{
TabItem ti = (TabItem)mainTab.Items[i];
if ("welcomeTabItem" != ti.Name)
{
mainTab.Items.Remove(ti);
}
}
Upvotes: 5
Reputation: 2597
Editing an Enumerable inside a Foreach is not allowed
You could use the below LINQ code, to remove all the items except "welcomeTabItem":
mainTab.Items.RemoveAll(i => i.Name != "welcomeTabItem");
Upvotes: 3
Reputation: 81243
You can use LINQ
to remove items like this -
mainTab.Items.RemoveAll(ti => ((TabItem)ti).Name != "welcomeTabItem");
Make sure to add using System.Linq;
namespace at top of your file.
Upvotes: 4
Reputation: 3785
You could get the desired item, then clear the control and add the item back.
// Note that `First` will throw an exception if the item isn't found.
TabItem ti = mainTab.Items.First(t => t.Name == "WelcomTabItem");
mainTab.Items.Clear();
mainTab.Items.Add(ti);
Alternatively, if "WelcomeTabItem" may not be in Items
:
TabItem ti = mainTab.Items.FirstOrDefault(t => t.Name == "WelcomTabItem");
mainTab.Items.Clear();
if(ti != null)
mainTab.Items.Add(ti);
Upvotes: 6
Reputation: 32459
Use the following code:
var itemsToRemove = new List(TabItem);
foreach (object item in mainTab.Items)
{
TabItem ti = (TabItem)item;
if ("welcomeTabItem" != ti.Name)
{
itemsToRemove.Add(item);
}
}
foreach (var itemToRemove in itemsToRemove)
{
mainTab.Items.Remove(itemToRemove);
}
You cannot remove items from a collection while you enumerating it
Upvotes: 1