Click here to Skip to main content
15,881,281 members
Articles / Web Development / CSS
Tip/Trick

Database Driven Dynamic Menu Control

Rate me:
Please Sign up or sign in to vote.
4.95/5 (19 votes)
15 Jan 2013CPOL3 min read 169.6K   7.1K   40   32
Database driven N-Level Dynamic Menu Control using C#.NET and SQL Server with stylesheet CSS

Introduction

As everyone knows, Menu is an important control in Visual Studio which is used in web based applications. Displaying hard coded or static menu on a web page is very easy, but showing menu on page dynamically is somewhat tricky. So I've decided to write some code which displays menu dynamically on page and also which is database driven.

Background

I've seen many developers who are in need of creating database driven dynamic menu and proper solution when code is not available. Many solutions are available, but up to 1 or 2 level hierarchy of menu. As shown in the below image, it is N-level Database Driven Dynamic Menu. This article will be very helpful for those who are looking for database driven dynamic menu. One can explore it more and more with user role or as per requirement.

Image 1

Using the Code

Step 1: Create a Table in SQL as script given below

SQL
CREATE TABLE [dbo].[menuMaster]
(
	[menu_id] [int] NOT NULL,
	[menu_name] [varchar](100) NOT NULL,
	[menu_parent_id] [int] NULL,
	[menu_url] [varchar](50) NULL,
        CONSTRAINT [PK_menuMaster] PRIMARY KEY CLUSTERED
	(
		[menu_id] ASC
	)
)

In the above table, menu_id is a unique incremental id which is Child Menu and menu_parent_id is the Parent Menu. In the above table, Roles are not included for keeping the simplicity. One can add new columns as per requirement and can use them in any way.

Step 2: Insert data into Table menuMaster

Please execute the below script to insert data into menuMaster table so that you can quickly view the data, how we are using data and it will also save your time. In the data given below, you can view that menu_parent_id is NULL for Root Menu. And for other menus, the parent id is mentioned in menu_parent_id column. Simply copy and paste in SQL editor and execute it.

SQL
insert into menuMaster values(1,'Home',NULL,NULL)
insert into menuMaster values(2,'Services',NULL,NULL)
insert into menuMaster values(3,'Products',NULL,NULL)
insert into menuMaster values(4,'Partners',NULL,NULL)
insert into menuMaster values(5,'Training',NULL,NULL)
insert into menuMaster values(6,'Resources',NULL,NULL)
insert into menuMaster values(7,'Support',NULL,NULL)
insert into menuMaster values(8,'Logout',NULL,NULL)
insert into menuMaster values(9,'Digital Certificate',2,'#')
insert into menuMaster values(10,'e-Procurement',2,'#')
insert into menuMaster values(11,'e-Governance',2,'#')
insert into menuMaster values(12,'Data Center',2,'#')
insert into menuMaster values(13,'CCTV & Surveillence',2,'#')
insert into menuMaster values(14,'Cloud Computing',2,'#')
insert into menuMaster values(15,'Test Procure',3,'#')
insert into menuMaster values(16,'Test Sign',3,'#')
insert into menuMaster values(17,'Test Tree',3,'#')
insert into menuMaster values(18,'Test Wrap',3,'#')
insert into menuMaster values(19,'Test Dorse',3,'#')
insert into menuMaster values(20,'Test Share',3,'#')
insert into menuMaster values(21,'Technology Partner',4,'#')
insert into menuMaster values(22,'Channel Partner',4,'#')
insert into menuMaster values(23,'Premium Partner',4,'#')
insert into menuMaster values(24,'Certificate Usage',5,'#')
insert into menuMaster values(25,'Download Procedure',5,'#')
insert into menuMaster values(26,'User Manual',5,'#')
insert into menuMaster values(27,'White Papers',6,'#')
insert into menuMaster values(28,'Download Drivers',6,'#')
insert into menuMaster values(29,'For DGFC Users',6,'#')
insert into menuMaster values(30,'Important Site Links',6,'#')
insert into menuMaster values(31,'Entrust',30,'http://www.entrust.com')
insert into menuMaster values(32,'CCA',30,'http://www.cca.gov.in')
insert into menuMaster values(33,'PKI Forum',30,'http://www.pkiforum.org')
insert into menuMaster values(34,'Telephonic Support',7,'#')
insert into menuMaster values(35,'FAQ',7,'#')
insert into menuMaster values(36,'Feedback',7,'#')

Step 3: Copy and paste the following CSS in file Named: TableTemplates.css

Below is the CSS which you have to copy and paste in TableTemplates.css file or whatever file name you want. But do not forgot to add a link of this CSS file on the master page or whatever page you are using menu control. You can add the below CSS on the page where you have placed the Menu control also. The best practice is to keep it in a separate file. The file is attached in zip format and can be downloaded from the link at the top of this article. The CSS is also given below.

CSS
.MenuBar { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; }

.StaticMenuItem 
{
    background-color: #1999cf;   -moz-border-radius: 1px;
    -webkit-border-radius: 1px;   font: 14pt calibri;
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    margin: auto; vertical-align: middle; background-repeat: repeat-x;
    height: 70px; text-align: center; color: white; padding: 5px;
}

.StaticMenuItemStyle { color: #ffffff; padding: 20px; }

 
.StaticHoverStyle { background-color: #b6e390; color: #5f5f5f; }

.StaticSelectedStyle { background-color: #ffe99f; color: #5f5f5f; }

.DynamicMenuItemStyle 
{ 
    background-color: #bdeafe; border-width: 1px; border-style: solid;
    border-color: #000000; -moz-border-radius: 1px; -webkit-border-radius: 1px;
    font: 13pt calibri; margin: auto;border-left: 0px solid #c1c1c1; 
    border-right: 0px solid #c1c1c1; border-top: 0px solid #c1c1c1;
    border-bottom: 1px solid #c1c1c1; border-spacing: 0px;
    vertical-align: middle; background-repeat: repeat-x;
    height: 50px; text-align: left; color: #5f5f5f; padding: 5px;
}

.DynamicHoverStyle { background-color: #eca74c; color: #ffffff; }

Step 4 : Add Menu control on Master page

Adding Style Sheet Link on Master Page.

HTML
<head runat="server">
    <title>Database Driven Dynamic Control</title>
    <link rel="Stylesheet" href="TableTemplates.css" 
    type="text/css" />
   
</head>

Adding of menu control will look like this. In the below code, we have simply added the Menu control and for using the CSS, we have given different CSS for example 'StaticMenuStyle', etc.

HTML
 <body>
    <form id="form1" runat="server">
        <div>
            <asp:Menu ID="menuBar" 
            runat="server" Orientation="Horizontal" 
Width="100%" 
CssClass="MenuBar" MaximumDynamicDisplayLevels="10">
                <StaticMenuStyle CssClass="StaticMenuItem" />
                <StaticMenuItemStyle CssClass="StaticMenuItemStyle" />
                <StaticHoverStyle CssClass="StaticHoverStyle" />  
                <StaticSelectedStyle CssClass="StaticSelectedStyle" />              
                <DynamicMenuItemStyle CssClass="DynamicMenuItemStyle" />
                <DynamicHoverStyle CssClass="DynamicHoverStyle" />
            </asp:Menu>
        </div>
        
    </form>
</body>

Step 5 : On page load, call the following function

Below is the code which you have to copy and paste in code behind.

C#
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetMenuData();
        }
    }

I've written a function named GetMenuData() where I've written the core logic of Dynamic.

C#
private void GetMenuData()
    {
        DataTable table = new DataTable();
        string strCon = System.Configuration.ConfigurationManager.ConnectionStrings
        ["cnstring"].ConnectionString;
        SqlConnection conn = new SqlConnection(strCon);
        string sql = "select menu_id, menu_name, menu_parent_id, menu_url from menuMaster";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(table);
        DataView view = new DataView(table);
        view.RowFilter = "menu_parent_id is NULL";
        foreach (DataRowView row in view)
        {
            MenuItem menuItem = new MenuItem(row["menu_name"].ToString(), 
            row["menu_id"].ToString());
            menuItem.NavigateUrl = row["menu_url"].ToString();
            menuBar.Items.Add(menuItem);
            AddChildItems(table, menuItem);
        }
    }

Calling method AddChildItem to fill menu up to N-level menu.

C#
private void AddChildItems(DataTable table, MenuItem menuItem)
   {
       DataView viewItem = new DataView(table);
       viewItem.RowFilter = "menu_parent_id=" + menuItem.Value;
       foreach (DataRowView childView in viewItem)
       {
           MenuItem childItem = new MenuItem(childView["menu_name"].ToString(),
           childView["menu_id"].ToString());
           childItem.NavigateUrl = childView["menu_url"].ToString();
           menuItem.ChildItems.Add(childItem);
           AddChildItems(table, childItem);
       }
   }

The only thing is you have to change the connection string in web.config file.

Note: A sample project zip file is attached. This project is built in VS2012 Express. But we can use menu control in any version.

License

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


Written By
Technical Lead
India India
Software Professional experience since 2006 in ASP.NET, VB.NET, C# .NET, SQL SERVER, ORACLE, MS ACCESS, Web Services, HTML, JQUERY and CRYSTAL REPORTS.

Expertise in developing web and Desktop applications.

Visit http://yugalpandya.wordpress.com for more information.

Comments and Discussions

 
QuestionInternet Explorer 8 Pin
RobertoTjMx6-Mar-13 10:02
RobertoTjMx6-Mar-13 10:02 
BugRe: Internet Explorer 8 Pin
Jimmy_Lee5-Sep-13 19:08
Jimmy_Lee5-Sep-13 19:08 
QuestionExcellent thank you Pin
Praveen Chirath25-Feb-13 18:49
Praveen Chirath25-Feb-13 18:49 
GeneralMy vote of 5 Pin
Yugal Pandya16-Jan-13 22:03
Yugal Pandya16-Jan-13 22:03 
Questionerror download source code Pin
hashemramsin13-Jan-13 19:48
hashemramsin13-Jan-13 19:48 
problem download source code!!!
Questionunable to download source Pin
samiatcodeproject13-Jan-13 1:52
samiatcodeproject13-Jan-13 1:52 
AnswerRe: unable to download source Pin
Yugal Pandya13-Jan-13 3:10
Yugal Pandya13-Jan-13 3:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.