How to remove menu items from ASP.Net menu?

In this post I will show code snippet for removing a menu item from ASP.Net Menu control. This kind of situation may arise when you want to authorize certain menu items based on some run time condition or user's role. One option is that you can add entries to Menu control at run time based on authorization rules. And then you have option of removing menu items if you have created your whole menu structure declartively.

Here is code snippet that shows how you can remove menu items from collection.

void AuthorizeMenuNavigation()
{
   List<MenuItem> itemsToRemove = new List<MenuItem>();
   foreach (MenuItem menuitem in NavigationMenu.Items)
   {
      if (menuitem.Value == "Manage")
      {
        itemsToRemove.Add(menuitem);
      }
   }

   foreach (var item in itemsToRemove)
   {
      NavigationMenu.Items.Remove(item);
   }
}

The reason it is done in two steps is because you can not remove items from a collection while iterating over it. Otherwise you will get an exception about "Collection was modified ....".

Search

Social

Weather

9.0 °C / 48.2 °F

weather conditions Clouds

Monthly Posts

Blog Tags