1
我想从数据库创建一个菜单并在菜单控制中显示。如何使用asp.net中的菜单控件从数据库创建动态菜单?
代码这里在.aspx页面中:
<asp:Menu ID="Menu1" Orientation="horizontal" StaticMenuItemStyle-CssClass="menuItem"
DynamicMenuItemStyle-CssClass="menuItem" runat="server">
在法师的.cs页:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateMenuItem();
}
}
private void populateMenuItem()
{
DataTable menuData = GetMenuData();
AddTopMenuItems(menuData);
}
/// Filter the data to get only the rows that have a
/// null ParentID (This will come on the top-level menu items)
private void AddTopMenuItems(DataTable menuData)
{
DataView view = new DataView(menuData);
view.RowFilter = "DepartmentParentID IS NULL";
foreach (DataRowView row in view)
{
//MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString());
MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString());
Menu1.Items.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}
}
//This code is used to recursively add child menu items by filtering by ParentID
private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem)
{
DataView view = new DataView(menuData);
view.RowFilter = "DepartmentParentID=" + parentMenuItem.Value;
foreach (DataRowView row in view)
{
MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString());
parentMenuItem.ChildItems.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}
}
private DataTable GetMenuData()
{
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT DepartmentID,OfficeID,DepartmentName,DepartmentParentID,IsActive,CreatedByID,CreatedDate,LastModifiedByID,LastModifiedDt FROM DepartmentMst", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
问题是在AddTopMenuItems()方法,其中显示“未将对象引用设置为实例的对象“在行Menu1.Items.Add(newMenuItem); 不知道为什么?
下面是数据在SQLSERVER2008 DepartmentMst:
DepartmentID DepartmentName IsActive DepartmentParentID
1 HR 1 NULL
2 IT 1 NULL
3 Operations 1 NULL
4 Desktop Engineer 1 2
5 Network Engineer 1 2
6 Employee Salary 1 1
当DepartmentParentID为NULL,则它是主菜单,如果不是null,则它与尊重其父ID子节点。
样品这里http://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/
帮助感激!
感谢@ Deni ...现在我知道了...... :) –
Plz告诉我如何从Master页面获取Content Page中的Selected MenuItem。例如:如果Department是“DesktopEngineer”,那么我需要它存储在数据库中的相应值? –
看看这篇文章 - http://stackoverflow.com/questions/2770042/set-item-selected-in-asp-net-menu-control –