I have a menu control (Menu1) and I want to add/remove items from the menu based on certain information I have stored about the authenticated user in the database. I'm not sure though how to access specific men开发者_JS百科u items from the menu control and remove them at runtime?
ASP.NET menus can be accessed via code behind. A menu declared in the markup, having the id 'Menu1' for example, could be accessed like so:
foreach (MenuItem item in Menu1.Items) {
if (item.NavigateUrl.Contains(pageName)) {
item.Selected = true;
item.Text = "customText";
}
// ...
}
In that example, the currently selected menu item is chosen according to the current page the menu is on. Just as well, the Items collection may be used to add or remove single menu items. Note, on menu items, the ChildItems collection can be used to alter the submenu items collection.
More infos: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.items.aspx
@Edit: made it more coherent with the data in the question
I wish you was more specific but I know that the notification for comments kinda sucks here. so if you could tell me exactly
- what is the information you'll Add/Remove items based on ?
- how are they're stored in the database (which means are they are stored in one of the membership tables ? in the profile's table ? or a custom table where the user is referenced in ?
- what's the technique you imagine in your mind in plain English ?
I'm not sure though how to access specific menu items from the menu control and remove them at runtime?
A. Remove items:
Menu1.Items.Remove(Menu1.FindItem("Jobs"))
B. Add Items:
Menu1.Items.Add(new MenuItem("News"))
OR use this to specify the required properties for the new added item:
MenuItem item = new MenuItem()
item.NavigateUrl =""
item.Text = "Child Test"
Menu1.Items.Add(mnuTestChild)
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
string selectCmd = "Select * from Pages where Status='"+1+"'";
SqlDataAdapter dap = new SqlDataAdapter(selectCmd,con);
DataSet ds = new DataSet();
dap.Fill(ds);
if (!Page.IsPostBack)
{
int x = 0;
string parent_id = "";
foreach (DataRow dr in ds.Tables[0].Rows)
{
parent_id = dr[0].ToString();
Menu1.Items.Add(new MenuItem(dr["Title"].ToString(), dr["URL"].ToString(), dr["ID"].ToString()));
}
x++;
}
}
精彩评论