In this article I will explain how to build a Database driven ASP.Net Menu control i.e. dynamically populating Menu items from the database in ASP.Net using C# and VB.Net.
The Menu items will be populated from database using recursion.
Database
I have made use of the following table Menus with the schema as follows.
I have already inserted few records in the table.
Note: You can have as many child levels as you want, here I am using 2 Level Menu structure.
Home => Home.aspx
Services
Consulting => Consulting.aspx
Outsourcing => Outsourcing.aspx
About => About.aspx
Contact => Contact.aspx
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
Below is the HTML Markup of the Master Page Main.Master that contains the Menu control.
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
<LevelMenuItemStyles>
<asp:MenuItemStyle CssClass="main_menu" />
<asp:MenuItemStyle CssClass="level_menu" />
</LevelMenuItemStyles>
<StaticSelectedStyle CssClass="selected" />
</asp:Menu>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Populating the ASP.Net Menu control items from database
The PopulateMenu method is a recursive function. Inside the Page Load event of the Master Page, the Menu control is populated with the records from the Menus table.
Inside the PopulateMenu method, a loop is executed over the DataTable and if the ParentMenuId is 0 i.e. the menu is a parent (root) menu, again a query is executed over the Menus table to populate the corresponding submenus and again the PopulateMenu method is called.
This process continues until all menus along with their submenus are added to the ASP.Net Menu control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData(0);
PopulateMenu(dt, 0, null);
}
}
private DataTable GetData(int parentMenuId)
{
string query = "SELECT [MenuId], [Title], [Description], [Url] FROM [Menus] WHERE ParentMenuId = @ParentMenuId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
DataTable dt = new DataTable();
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("@ParentMenuId", parentMenuId);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
private void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
{
string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
foreach (DataRow row in dt.Rows)
{
MenuItem menuItem = new MenuItem
{
Value = row["MenuId"].ToString(),
Text = row["Title"].ToString(),
NavigateUrl = row["Url"].ToString(),
Selected = row["Url"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
};
if (parentMenuId == 0)
{
Menu1.Items.Add(menuItem);
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
else
{
parentMenuItem.ChildItems.Add(menuItem);
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData(0)
PopulateMenu(dt, 0, Nothing)
End If
End Sub
Private Function GetData(parentMenuId As Integer) As DataTable
Dim query As String = "SELECT [MenuId], [Title], [Description], [Url] FROM [Menus] WHERE ParentMenuId = @ParentMenuId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Dim dt As New DataTable()
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.Parameters.AddWithValue("@ParentMenuId", parentMenuId)
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
Private Sub PopulateMenu(dt As DataTable, parentMenuId As Integer, parentMenuItem As MenuItem)
Dim currentPage As String = Path.GetFileName(Request.Url.AbsolutePath)
For Each row As DataRow In dt.Rows
Dim menuItem As New MenuItem() With { _
.Value = row("MenuId").ToString(), _
.Text = row("Title").ToString(), _
.NavigateUrl = row("Url").ToString(), _
.Selected = row("Url").ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase) _
}
If parentMenuId = 0 Then
Menu1.Items.Add(menuItem)
Dim dtChild As DataTable = Me.GetData(Integer.Parse(menuItem.Value))
PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
Else
parentMenuItem.ChildItems.Add(menuItem)
End If
Next
End Sub
Styling the ASP.Net Menu Control
I have placed the following CSS style in the Head section of the Master Page. You can also make use of an external CSS class file.
In the HTML Markup section you will notice I have specified LevelMenuItemStyles tag, which consists of two MenuItemStyle nodes. The first one is for the CSS Class of the top level or main menu and the second one is for the child or submenu.
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
color: #444;
}
.main_menu, .main_menu:hover
{
width: 100px;
background-color: #fff;
color: #333;
text-align: center;
height: 30px;
line-height: 30px;
margin-right: 5px;
}
.main_menu:hover
{
background-color: #ccc;
}
.level_menu, .level_menu:hover
{
width: 110px;
background-color: #fff;
color: #333;
text-align: center;
height: 30px;
line-height: 30px;
margin-top: 5px;
}
.level_menu:hover
{
background-color: #ccc;
}
.selected, .selected:hover
{
background-color: #A6A6A6 !important;
color: #fff;
}
.level2
{
background-color: #fff;
}
</style>
Demo
Downloads