• Now Online : 86
  • admin@codemyne.net

Introduction

The Menu control in Asp.Net is used to display a menu in an ASP.NET Web page and is often used in combination with a SiteMapDataSource control for navigating a Web site. The Menu control supports the following features:

  • Data binding that allows the control's menu items to be bound to hierarchal data sources.
  • Site navigation through integration with the SiteMapDataSource control.
  • Programmatic access to the Menu object model to dynamically create menus, populate menu items, set properties, and so on.
  • Customizable appearance through themes, user-defined images, styles, and user-defined templates.

Creating Dynamic Menu

This article explains about creation of dynamic menu using a database or a dynamic datatable. The steps involved in creation of dynamic menu are:

  1. Creating a hierarchical datatable dynamically. you can create it from a database also.
  2. Assigning this datatable to a DataSet
  3. Creating a parent/child relation to the datatable in the dataset
  4. Creating a .xslt file
  5. Binding xmldata that get by dataset to a xmlDatasource
  6. Reformat the xmldatasource to fit menu into xml format
  7. Assigning the path to start read all MenuItem under MenuItems
  8. Finally, bind the source to the Menu control

XSLT: XSLT is a language for transforming XML documents into XHTML documents or to other XML documents. XSLT is one part of XSL. XSL stands for EXtensible Stylesheet Language. XSL describes how the XML document should be displayed.

We will see all about XSL, XSLT, XPah, XSL-FO in another article.

The complete application to generate a dynamic menu is given below. And also you can download the sample code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DynamicMenu._Default" %>
<%--Example by www.codemyne.net--%>
<!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>Generating a dynamic menu in Asp.Net - Codemyne</title>
</head>
<body>
<form id="form1" runat="server">
<div >
<asp:Menu ID="Menu1" runat="server" 
Orientation="Horizontal" 
Font-Names="Verdana" Font-Size="12px" ForeColor="DarkBlue" 
StaticSubMenuIndent="10px" >
<StaticSelectedStyle BackColor="#5D7B9D"  />                  
<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
<DynamicHoverStyle BackColor="#FF9900" ForeColor="White" />
<DynamicMenuStyle BackColor="#1968A0" Width="150px" />
<DynamicSelectedStyle BackColor="#5D7B9D" />
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="5px" 
Width="150px"  />
<DataBindings>                    
<asp:MenuItemBinding TextField="MenuText" NavigateUrlField ="destUrl" ToolTipField="tooltip" />
</DataBindings>                                             
<StaticHoverStyle  ForeColor="Red" />
</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;
    namespace DynamicMenu
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {         
                if (!IsPostBack)
                {
                    DataTable dtMenu = new DataTable();
                    DataSet ds = new DataSet();
                    XmlDataSource xmlDataSource = new XmlDataSource();
                    xmlDataSource.ID = "XmlSource1";
                    xmlDataSource.EnableCaching = false;
                    dtMenu = GetMenuTable();
                    ds.Tables.Add(dtMenu);
                    ds.DataSetName = "Menus";
                    ds.Tables[0].TableName = "Menu";
                    DataRelation relation = new DataRelation("Parentchild", ds.Tables["Menu"].Columns["Id"], ds.Tables["Menu"].Columns["ParentId"], true);
                    relation.Nested = true;
                    ds.Relations.Add(relation);
                    xmlDataSource.Data = ds.GetXml();
                    //Reformat the xmldatasource from the dataset to fit menu into xml format
                    xmlDataSource.TransformFile = Server.MapPath("~/Menu.xslt");
                    //assigning the path to start read all MenuItem under MenuItems
                    xmlDataSource.XPath = "MenuItems/MenuItem";
                    //Finally, bind the source to the Menu1 control
                    Menu1.DataSource = xmlDataSource;
                    Menu1.DataBind();
                }
            }
            private DataTable GetMenuTable()
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Id", Type.GetType("System.Int16"));
                dt.Columns.Add("ParentId", Type.GetType("System.Int16"));
                dt.Columns.Add("Name", Type.GetType("System.String"));         
                dt.Columns.Add("ToolTip", Type.GetType("System.String"));
                dt.Columns.Add("NavigateUrl", Type.GetType("System.String"));
                DataColumn[] dcArray = new DataColumn[1];
                dcArray[0] = dt.Columns[0];
                dt.PrimaryKey = dcArray;
                DataRow dr;
                dr = dt.NewRow();
                dr[0] = 1;
                dr[1] = DBNull.Value;
                dr[2] = "Home";        
                dr[3] = "Click here to go to Home";
                dr[4] = "~/Default.aspx";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr[0] = 2;
                dr[1] = DBNull.Value;
                dr[2] = "Services";         
                dr[3] = "Click here to go to Services";
                dr[4] = "~/Services.aspx";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr[0] = 3;
                dr[1] = DBNull.Value;
                dr[2] = "Contactus";        
                dr[3] = "Click here to go to Contactus";
                dr[4] = "~/Contactus.aspx";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr[0] = 4;
                dr[1] = 2;
                dr[2] = "Web Designing";          
                dr[3] = "Click here to go to Web Designing";
                dr[4] = "~/WebDesign.aspx";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr[0] = 5;
                dr[1] = 2;
                dr[2] = "Web Development";          
                dr[3] = "Click here to go to Web Development";
                dr[4] = "~/WebDevelopment.aspx";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr[0] = 6;
                dr[1] = 2;
                dr[2] = "OutSourcing";          
                dr[3] = "Click here to go to Outsourcing";
                dr[4] = "~/Outsourcing.aspx";
                dt.Rows.Add(dr);
                return dt;
            }
           
        }
    }
    
    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes" encoding="utf-8"/>
    <!-- Find the root node called Menus
          and call MenuListing for its children -->
    <xsl:template match="/Menus">
    <MenuItems>
    <xsl:call-template name="MenuListing" />
    </MenuItems>
    </xsl:template>
    <!-- Allow for recusive child node processing -->
    <xsl:template name="MenuListing">
    <xsl:apply-templates select="Menu" />
    </xsl:template>
    <xsl:template match="Menu">
    <MenuItem>
    <!-- Convert Menu child elements to MenuItem attributes -->
    <xsl:attribute name="MenuText">
    <xsl:value-of select="Name"/>
    </xsl:attribute>
    <xsl:attribute name="tooltip">
    <xsl:value-of select="ToolTip"/>
    </xsl:attribute>
    <xsl:attribute name="destUrl">
    <xsl:value-of select="NavigateUrl"/>
    </xsl:attribute>
    <!-- Call MenuListing if there are child Menu nodes -->
    <xsl:if test="count(Menu) > 0">
    <xsl:call-template name="MenuListing" />
    </xsl:if>
    </MenuItem>
    </xsl:template>
       
    </xsl:stylesheet>
    

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment

raveena_ff 12/2/2010 (IST) / Reply

Good, Really Thanks. By. D.Ravi

ramu 12/7/2010 (IST) / Reply

hi please support me

raj 1/6/2011 (IST) / Reply

Good, Really Thanks

Brindha 4/21/2011 (IST) / Reply

Hi.. This is very simple and easy to understane for the beginners. Thanks for the coding..

Anish 9/30/2011 (IST) / Reply

Good Work. It Helped Me alot

Abdul Majeed 11/19/2011 (IST) / Reply

Have a nice code example

Balakrishnan 12/2/2011 (IST) / Reply

hi..This article was really awesome. You have any idea of Creating multi-nested Dynamic Menu which drives values from Sql Server database?

Raquib 2/2/2012 (IST) / Reply

Thanks

Sachin 2/16/2012 (IST) / Reply

Thanks Realy nice :

lalit yadav 3/26/2012 (IST) / Reply

abc

pawan dhawan 3/27/2012 (IST) / Reply

Good example

Pawan Dhawan 3/28/2012 (IST) / Reply

menu

sinu 4/16/2012 (IST) / Reply

thanksss

obe 4/28/2012 (IST) / Reply

thanks

Divesh 5/4/2012 (IST) / Reply

Really gud..... Can u explain the xslt pat...

balram 5/19/2012 (IST) / Reply

i need help to create dynamic menu

webmaster 5/20/2012 (IST) / Reply

To Balram: We are already published this article on how to create a dynamic menu in asp.net.If it is not fulfills your need, please tell us on what technology you need this requirement.

babu 5/23/2012 (IST) / Reply

All is well

gaurav 7/10/2012 (IST) / Reply

how to create dynamic menus in asp.net

kamran 7/23/2012 (IST) / Reply

ds

Nikunj Sharma 7/29/2012 (IST) / Reply

My Question is i have to bind dynamic menu using ul tag but menu not to bind properly give me your answer please. I have so much confuse. how to resolve it.

renuk 7/31/2012 (IST) / Reply

Hi Nikunj Sharma .. please describe your problem clearly. So that we can help you.

anil 8/14/2012 (IST) / Reply

thanks for code

Sunil 8/18/2012 (IST) / Reply

req code for sample

gn 8/22/2012 (IST) / Reply

gh

Jitendra Kumar 5/19/2013 (IST) / Reply

Greate Work, Very Helpfull! Thanks!

Ravi 6/24/2013 (IST) / Reply

Help For Menu

ayub 2/6/2015 (IST) / Reply

create dynamic menu