manuthalasseril
manuthalasseril

Reputation: 1064

How to remove all tab items except one in wpf?

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

Answers (5)

Hossein Narimani Rad
Hossein Narimani Rad

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

jacob aloysious
jacob aloysious

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

Rohit Vats
Rohit Vats

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

Jason Watkins
Jason Watkins

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

Andrey Gordeev
Andrey Gordeev

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

Related Questions