Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET / ASP.NET4.0

Generating menu from database according to user privilege

Rate me:
Please Sign up or sign in to vote.
4.97/5 (23 votes)
25 Sep 2012CPOL3 min read 127.3K   5.6K   47  
Dynamic menu generation according to user privileges from database.
#region Namespaces
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.Data.SqlClient;
using System.Configuration;
#endregion

public partial class Home : System.Web.UI.Page
{
    #region Page Load
    /// <summary>
    /// Loads the intial initial contents required for the page
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable menuData = null;
            try
            {
                menuData = new DataTable();
                menuData = GetMenuData();
                AddTopMenuItems(menuData);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                menuData = null;
            }
        }
    }
    #endregion

    #region Function for getting data for menu
    /// <summary>
    /// Get's the data from database for menu
    /// </summary>
    /// <returns>Datatable of menu items</returns>
    private DataTable GetMenuData()
    {
        try
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MenuWithCustomPrivs"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("spMenuItem", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@UserID", "K010");
                DataTable dtMenuItems = new DataTable();
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(dtMenuItems);
                cmd.Dispose();
                sda.Dispose();
                return dtMenuItems;
            }
        }
        catch (Exception ex) {
            Response.Write(ex.Message);
        }
        return null;
    }
    #endregion

    #region Function for adding top menu items
    /// <summary>
    /// Adds the top/parent menu items for the menu
    /// </summary>
    /// <param name="menuData"></param>
    private void AddTopMenuItems(DataTable menuData)
    {
        DataView view = null;
        try
        {
            view = new DataView(menuData);
            view.RowFilter = "ParentID IS NULL";
            foreach (DataRowView row in view)
            {
                //Adding the menu item
                MenuItem newMenuItem = new MenuItem(row["Text"].ToString(), row["MenuID"].ToString());
                menuBar.Items.Add(newMenuItem);
                AddChildMenuItems(menuData, newMenuItem);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally {
            view = null;
        }
    }
    #endregion

    #region Function for adding child menu items from database
    /// <summary>
    /// This code is used to recursively add child menu items by filtering by ParentID
    /// </summary>
    /// <param name="menuData"></param>
    /// <param name="parentMenuItem"></param>
    private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem)
    {
        DataView view = null;
        try
        {
            view = new DataView(menuData);
            view.RowFilter = "ParentID=" + parentMenuItem.Value;
            foreach (DataRowView row in view)
            {
                MenuItem newMenuItem = new MenuItem(row["Text"].ToString(), row["MenuID"].ToString());
                newMenuItem.NavigateUrl = row["NavigateUrl"].ToString();
                parentMenuItem.ChildItems.Add(newMenuItem);
                
                AddChildMenuItems(menuData, newMenuItem);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            view = null;
        }
    }
    #endregion
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Malaysia Malaysia
I've been working with various Microsoft Technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an attitude for learning new skills and utilizing that in my work.


--Amit Kumar
You can reach me at:
Facebook | Linkedin | Twitter | Google+

Comments and Discussions