我想从数据库创建一个菜单并在菜单控件中显示。
.aspx 页面中的代码:
 <asp:Menu ID="Menu1" Orientation="horizontal" StaticMenuItemStyle-CssClass="menuItem"
                            DynamicMenuItemStyle-CssClass="menuItem" runat="server">
在 Master 的 .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 时,它是 Main Menu,如果不为 null,则它是 Child 节点,并尊重其 Parent ID。
示例http://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/
帮助赞赏!