Unable to remove menu item from Asp Menu

Posted by Sharpcnet under C# on 12/18/2013 | Points: 10 | Views : 2209 | Status : [Member] | Replies : 1
ASPX:
<asp:Menu id ="menuBar" runat="server" Orientation="Horizontal" 
IncludeStyleBlock="false">
<item>
<asp:MenuItem Text="Home"></asp:MenuItem>
<asp:MenuItem Text="Folio">
<asp:MenuItem Text="Nature" NavigateUrl="#" value="1"></asp:MenuItem>
<asp:MenuItem Text="People" NavigateUrl="#" value="2"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Contact">
<asp:MenuItem Text="admin" NavigateUrl="#" value="3"></asp:MenuItem>
</asp:MenuItem>
</items>
</asp:Menu>
C#:
protected void page_load(object sender, eventargs e)
{
List<tblDetal> lstDetail = objDal.GetData();
foreach(MenuItem parent in menuBar.Items)
{
if(parent.ChildItems.Count > 0)
{
foreach(MenuItem child in parent.ChildItems)
{
bool showItem = false;
foreach(var item in lstDetail)
{
if(convert.toint32(child.value)==item.FormId)
{
showItem = true;
break;
}
}
if(showItem==false)
parent.ChildItems.Remove(child);
}
}
}
}

That was my simple code to remove items from menu based on some criterion.
After the compiler reads, the 'remove' line, it goes back to the foreach loop and then it errors out with - "Collection was modified. Enumeration opearion may not execute.".

I understand that, but dont know how to fix this. If it was just one item to be removed, that would have been easier.




Responses

Posted by: vishalneeraj-24503 on: 12/18/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Try
Hi you can try this
public void DisplayMenuTabs()
{
if (Session["Menu1Access"].ToString() == "True")
Menu1.Visible = true;
else
Menu1.Visible = false;
if (Session["Menu2Access"].ToString() == "True")
Menu2.Visible = true;
else
Menu2.Visible = false;
if (Session["Menu3Access"].ToString() == "True")
Menu3.Visible = true;
else
Menu3.Visible = false;
}

//Or you can find your menu as below
Menu myMenu = (Menu)Master.FindControl("menu1");
myMenu.Visible=false;

//Or you can also try

MenuItemCollection menuItems = mTopMenu.Items;
MenuItem adminItem = new MenuItem();
foreach (MenuItem menuItem in menuItems)
{
if (menuItem.Text == "Roles")
adminItem = menuItem;
}
menuItems.Remove(adminItem);

//Or do the following

MenuItem item = NavigationMenu.FindItem("Users/Manage Accounts");
item.Parent.ChildItems.Remove(item);

Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response