【问题标题】:How to Create Dynamic Menu from Database using Menu control in asp.net?如何使用 asp.net 中的菜单控件从数据库创建动态菜单?
【发布时间】:2012-10-31 16:47:04
【问题描述】:

我想从数据库创建一个菜单并显示在菜单控件中。

.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 时,它是主菜单,如果不为 null,则它是子节点,并尊重其父 ID。

这里的示例http://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/

帮助赞赏!

【问题讨论】:

    标签: asp.net recursion menu menuitem


    【解决方案1】:
        **Creating Dynamic CSS Menu From Database SQL Server in ASP.Net Using C#.Net OR create dynamically menu and submenu from database in asp .net**
    
        <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicCSSMenu.aspx.cs" Inherits="DynamicCSSMenu" %>
    
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head runat="server">
            <title>Creating Dynamic CSS Menu From Database SQL Server in ASP.Net Using C#.Net/VB.NET
            </title>
            <style type="text/css">
                .ParentMenu
                {
                    font-size: small;
                    font-family: Tahoma;
                    font-weight: bold;
                    padding-left: 6px;
                    padding-right: 6px;
                    text-align: center;
                    background-color: #8B008B;
                    color: White;
                    border: 1px solid black;
                }
    
                .ParentMenu:hover
                {
                    font-family: Tahoma;
                    font-weight: bold;
                    padding-left: 6px;
                    padding-right: 6px;
                    text-align: center;
                    border: 1px solid black;
                    font-size: small;
                }
    
                .ChildMenu
                {
                    background-color: #8B008B;
                    font-weight: bold;
                    font-family: Tahoma;
                    padding-top: 4px;
                    padding-bottom: 4px;
                    padding-right: 5px;
                    padding-left: 5px;
                    text-align: left;
                    font-size: small;
                    color: White;
                    border: 1px solid black;
                }
                .ChildMenu:hover
                {
                    font-weight: bold;
                    font-family: Tahoma;
                    padding-top: 4px;
                    padding-bottom: 4px;
                    padding-right: 6px;
                    padding-left: 6px;
                    text-align: left;
                    font-size: small;
                    border: 1px solid black;
                    background-color: Black;
                }
            </style>
        </head>
        <body>
            <form id="form1" runat="server">
            <div>
                <asp:Menu DynamicSelectedStyle-Font-Italic="true" ID="dynamicMENU" runat="server"
                    Orientation="Horizontal" DynamicVerticalOffset="4" OnMenuItemClick="dynamicMENU_MenuItemClick">
                    <StaticMenuItemStyle Width="100" CssClass="ParentMenu" />
                    <DynamicMenuItemStyle Width="250" CssClass="ChildMenu" />
                </asp:Menu>
            </div>
            </form>
        </body>
        </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Configuration;
    using System.Data.SqlClient;
    
    public partial class DynamicCSSMenu : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetMenu();
            }
        }
    
        public void GetMenu()
        {
            DataSet dsParentMenu = getPARENTMENU();
            DataRowCollection drcParentMenu = dsParentMenu.Tables[0].Rows;
            DataSet dsChildMenuAll = getCHILDMENU();
            DataTable drcChildMenuAll = dsChildMenuAll.Tables[0];
    
            MenuItem mainMENUITEM;
            MenuItem childMENUITEM;
            foreach (DataRow drParentMenu in drcParentMenu)
            {
                mainMENUITEM = new MenuItem(drParentMenu["ParentMenu_Name"].ToString());
                dynamicMENU.Items.Add(mainMENUITEM);
                DataRow[] drcChildMenu = drcChildMenuAll.Select("Parent_ID=" + "'" + drParentMenu["ID"].ToString() + "'");
                foreach (DataRow drSUBMENUITEM in drcChildMenu)
                {
                    childMENUITEM = new MenuItem(drSUBMENUITEM["ChildMenu_Name"].ToString());
                    mainMENUITEM.ChildItems.Add(childMENUITEM);
    
                    childMENUITEM.NavigateUrl = drSUBMENUITEM["ChildMenu_URL"].ToString();
                }
            }
            mainMENUITEM = new MenuItem("Logout");
            dynamicMENU.Items.Add(mainMENUITEM);
        }
    
        public DataSet getPARENTMENU()
        {
            SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString());
            string str_query = string.Empty;
            str_query = "SELECT * FROM Parent_Menu";
            SqlDataAdapter daPARENT = new SqlDataAdapter(str_query, myConnection);
            DataSet dsTEMP = new DataSet();
            daPARENT.Fill(dsTEMP, "tablePARENT");
            return dsTEMP;
        }
    
        public DataSet getCHILDMENU()
        {
            SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString());
            string str_querychild = string.Empty;
            str_querychild = "SELECT * FROM Child_Menu";
            SqlDataAdapter daCHILD = new SqlDataAdapter(str_querychild, myConnection);
            DataSet dsTEMP = new DataSet();
            daCHILD.Fill(dsTEMP, "tableCHILD");
            return dsTEMP;
        }
        protected void dynamicMENU_MenuItemClick(object sender, MenuEventArgs e)
        {
            Response.Redirect("~/index.aspx");
        }
    }
    

    【讨论】:

      【解决方案2】:

      我怀疑您已将菜单控件放在母版页的内容占位符中:

      <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                  <asp:Menu ID="Menu1" Orientation="horizontal" StaticMenuItemStyle-CssClass="menuItem"
                      DynamicMenuItemStyle-CssClass="menuItem" runat="server" />
              </asp:ContentPlaceHolder>
      

      ContentPlaceHolder 控件用于定义母版页的一个区域,该区域可以被与母版页关联的另一个页面的内容替换(显示子页)。

      由于菜单将是从母版页继承的所有页面之间的共享控件,只需将菜单移动到内容占位符外部的任何位置,您就可以开始了:

      <asp:Menu ID="Menu1" Orientation="horizontal" StaticMenuItemStyle-CssClass="menuItem"
          DynamicMenuItemStyle-CssClass="menuItem" runat="server" />
      <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
      </asp:ContentPlaceHolder>
      

      【讨论】:

      • 请告诉我如何从母版页获取内容页中的选定菜单项。例如:如果部门是“DesktopEngineer”,那么我需要存储在数据库中的相应值吗?
      • 我这里没有使用站点地图,我正在从 SQLServer 表中填充菜单....那么如何获取 Current MenuItem Selected 值的值?
      • 好的,这是一个与原始问题完全不同的问题。我建议发布一个新问题,我相信社区中的某个人会非常乐意为您提供帮助
      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2018-09-30
      • 2016-04-29
      • 2011-07-04
      相关资源
      最近更新 更多