Click here to Skip to main content
15,881,757 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

 
Questionthank u so much it worked properly ! definetly recommend it. others dont work at all ! Pin
Member 114714954-Feb-21 0:46
Member 114714954-Feb-21 0:46 
Questionmodel view controller Pin
Member 1125385720-Oct-16 7:25
Member 1125385720-Oct-16 7:25 
Questionerror : missing operand after = ??? Pin
Member 119963552-Sep-16 23:01
Member 119963552-Sep-16 23:01 
AnswerRe: error : missing operand after = ??? Pin
Member 119963552-Sep-16 23:03
Member 119963552-Sep-16 23:03 
QuestionDatabase Driven Dynamic Menu Control Pin
Member 1125385731-Aug-16 5:54
Member 1125385731-Aug-16 5:54 
QuestionIssue in child menu display on IIS Pin
KhushiC20-Apr-16 1:35
KhushiC20-Apr-16 1:35 
Questionquery Pin
Member 1199391418-Sep-15 0:55
Member 1199391418-Sep-15 0:55 
QuestionThank u it helped me alot Pin
pavan122612-May-15 18:45
pavan122612-May-15 18:45 
QuestionThank you Pin
cabdi5522-Dec-14 4:09
cabdi5522-Dec-14 4:09 
QuestionClick Event For navigation Menu... Pin
Arvind Gaud6-Sep-14 22:00
Arvind Gaud6-Sep-14 22:00 
Bugonclick on menu it open with previous link "http://localhost:65329/Mymenu/" i don't want this + new tab should open Pin
Yogesh Jumani20-Jun-14 17:58
Yogesh Jumani20-Jun-14 17:58 
QuestionUnable to run this code Pin
ADI@3453-Jun-14 15:28
ADI@3453-Jun-14 15:28 
QuestionDatabase Driven Dynamic Menu Control - CodeProject Pin
sachinbhangale25-May-14 21:00
sachinbhangale25-May-14 21:00 
Questiondatabase connectivity in c# Pin
Member 1064675330-Apr-14 16:31
Member 1064675330-Apr-14 16:31 
GeneralVote for this example is 3 Pin
santosh panchal14-Apr-14 0:25
santosh panchal14-Apr-14 0:25 
Questionadd image as anchor to base level menu Pin
dawahab15-Jan-14 22:51
dawahab15-Jan-14 22:51 
Questiondynamic menu Pin
Member 105006726-Jan-14 0:27
professionalMember 105006726-Jan-14 0:27 
QuestionExcellent Pin
Member 1049444530-Dec-13 1:48
Member 1049444530-Dec-13 1:48 
GeneralMy vote of 5 Pin
rafa.el27-Sep-13 6:55
rafa.el27-Sep-13 6:55 
QuestionWorking great, but I got problem on my Popup window Pin
Dimaz Janu5-Sep-13 16:27
Dimaz Janu5-Sep-13 16:27 
Questionnavigation Pin
Codes DeCodes25-Aug-13 20:44
Codes DeCodes25-Aug-13 20:44 
GeneralThanks Pin
poir045027-Jun-13 5:17
poir045027-Jun-13 5:17 
QuestionThis is really helpful thank you Pin
Rakesh S Parmar9-May-13 3:40
Rakesh S Parmar9-May-13 3:40 
Questionabout control used Pin
Prasanna Rajendra Newaskar19-Apr-13 19:23
professionalPrasanna Rajendra Newaskar19-Apr-13 19:23 
AnswerRe: about control used Pin
Yugal Pandya3-Jul-13 0:21
Yugal Pandya3-Jul-13 0:21 

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.