Dynamic Menu In Asp.Net

How To Create Dynamic Menu In Asp.Net

In this tutorial we will learn How To Create Dynamic Menu In Asp.Net. Here we have used MS SQL Server as backend. First we have to create a table named menuitems. Here we are using asp.net menu control.

Earlier we have discussed  ,  , .

Dynamic menu In Asp.net

Menuitems Table:

create table menuitems
menuid int,
manuname nvarchar(50),
manulocation nvarchar(50),
parentid int

In below mentioned design, you can change color of menu according to your convenience, you just have to edit CSS on head tag.

Design View:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How To Create Dynamic Menu In Asp.Net</title>
<style type="text/css">
 width: 980px;
 margin: 0px auto;
 text-align: center;
 padding-top: 50px;
 font-size: 20px;
#menuBar { width:100%; }
#menuBar a { text-decoration:none;display:block;width:150px;font-family:Calibri;font-size:14px;background-color:#0094ff;color:#fff;padding:5px }
#menuBar a.static { text-decoration:none;border-style:none;margin-left:1px }
#menuBar a.dynamic { text-decoration:none;border-style:none;float:left;padding-top:5px;margin-top:1px;margin-left:2px }

<form id="form1" runat="server">
<h2>How To Create Dynamic Menu In Asp.Net</h2>    
<div class="MenuBar">
	<asp:Menu ID="menuBar" runat="server" Orientation="Horizontal" Width="100%">
<DynamicHoverStyle CssClass="DynamicHover" />
		<DynamicMenuItemStyle CssClass="DynamicMenuItem" />
		<DynamicSelectedStyle CssClass="DynamicHover" />

<br /><br />
<br /><br />
All rights reserved by <a href="http://www.hightechnology.in">www.Hightechnology.in</a>
| Hosting partner <a href="http://www.grootstech.com" target="_blank">Grootstech</a>    

Using the below mentioned code, you are pulling the menu and submenu from the database in proper order. Call the getMenu() the Page_Load event.


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
    string conn= ConfigurationManager.ConnectionStrings["connnn"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    private void getMenu()
        SqlConnection con = new SqlConnection(conn);
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        string sql = "Select * from menuitems";
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        dt = ds.Tables[0];
        DataRow[] drowpar = dt.Select("ParentID=" + 0);

        foreach (DataRow dr in drowpar)
            menuBar.Items.Add(new MenuItem(dr["ManuName"].ToString(),
                    dr["MenuID"].ToString(), "",