Dynamically populate ASP.Net Menu using UserControl in MasterPage using C# and VB.Net

varun.p
 
on Jan 13, 2019 10:43 PM
Sample_102987.zip
8021 Views

i want create dynamic menus using usercontrol in master page and it call on aspx page.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
pandeyism
 
on Jan 14, 2019 03:55 AM

Hey varun.p,

Please refer below sample.

Database

I have made use of the following table Menus with the schema as follows.

 I have already inserted few records in the table.

You can download the database table SQL by clicking the download link below.

Download SQL file

HTML

UserControl.aspx

<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" class="menu_Menu1">
    <LevelMenuItemStyles>
        <asp:MenuItemStyle CssClass="main_menu" />
        <asp:MenuItemStyle CssClass="level_menu" />
    </LevelMenuItemStyles>
    <StaticSelectedStyle CssClass="selected" />
</asp:Menu>

MasterPage.aspx

<%@ Register Src="~/WebUserControl.ascx" TagPrefix="uc1" TagName="MenuUC" %>
<!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></title>    
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
            color: #444;
        }
        .menu_Menu1 > ul, .menu_Menu1 > ul li, .menu_Menu1 > ul ul
        {
            list-style: none;
            margin: 0;
            padding: 0;
        }
        .menu_Menu1 > ul
        {
            position: relative;
            z-index: 597;
        }
        .menu_Menu1 > ul li
        {
            float: left;
            min-height: 1px;
            line-height: 1.3em;
            vertical-align: middle;
        }
        .menu_Menu1 > ul li.hover, .menu_Menu1 > ul li:hover
        {
            position: relative;
            z-index: 599;
            cursor: default;
        }
        .menu_Menu1 > ul ul
        {
            visibility: hidden;
            position: absolute;
            top: 100%;
            left: 0;
            z-index: 598;
            width: 100%;
        }
        .menu_Menu1 > ul ul li
        {
            float: none;
        }
        .menu_Menu1 > ul ul ul
        {
            top: 1px;
            left: 99%;
        }
        .menu_Menu1 > ul li:hover > ul
        {
            visibility: visible;
        }
        .menu_Menu1 > ul > li.last ul ul
        {
            left: auto !important;
            right: 99%;
        }
        .menu_Menu1 > ul > li.last ul
        {
            left: auto;
            right: 0;
        }
        .menu_Menu1 > ul > li.last
        {
            text-align: right;
        }
        .menu_Menu1 > ul
        {
            font-family: Calibri, Tahoma, Arial, sans-serif;
            font-size: 15px;
            background: #1e1e1e;
            background: -moz-linear-gradient(top, #1e1e1e 0%, #040404 100%);
            background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #1e1e1e), color-stop(100%, #040404));
            background: -webkit-linear-gradient(top, #1e1e1e 0%, #040404 100%);
            background: linear-gradient(top, #1e1e1e 0%, #040404 100%);
        }
        .menu_Menu1 > ul:before
        {
            content: '';
            display: block;
        }
        .menu_Menu1 > ul:after
        {
            content: '';
            display: table;
            clear: both;
        }
        .menu_Menu1 > ul li a
        {
            display: inline-block;
            padding: 10px 22px;
        }
        .menu_Menu1 > ul > li.active, .menu_Menu1 > ul > li.active:hover
        {
            background-color: #3fa338;
        }
        .menu_Menu1 > ul > li > a:link, .menu_Menu1 > ul > li > a:active, .menu_Menu1 > ul > li > a:visited
        {
            color: #ffffff;
        }
        .menu_Menu1 > ul > li > a:hover
        {
            color: #000000;
        }
        .menu_Menu1 > ul ul ul
        {
            top: 0;
        }
        .menu_Menu1 > ul li li
        {
            background-color: #ccc;
            border-bottom: 1px solid #ebebeb;
            font-size: 15px;
        }
        .menu_Menu1 > ul li.hover, .menu_Menu1 > ul li:hover
        {
            background-color: #F5F5F5;
        }
        .menu_Menu1 > ul > li.hover, .menu_Menu1 > ul > li:hover
        {
            background-color: #3fa338;
            -webkit-box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.15);
            -moz-box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.15);
            box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.15);
        }
        .menu_Menu1 > ul a:link, .menu_Menu1 > ul a:visited
        {
            color: #000000;
            text-decoration: none;
        }
        .menu_Menu1 > ul a:hover
        {
            color: #000000;
        }
        .menu_Menu1 > ul a:active
        {
            color: #9a9a9a;
        }
        .menu_Menu1 > ul ul
        {
            border: 1px solid #CCC;
            -webkit-box-shadow: 0 0px 2px 1px rgba(0, 0, 0, 0.15);
            -moz-box-shadow: 0 0px 2px 1px rgba(0, 0, 0, 0.15);
            box-shadow: 0 0px 2px 1px rgba(0, 0, 0, 0.15);
            width: 150px;
        }
    </style>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:MenuUC runat="server" ID="menu" />
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

Default.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.master" AutoEventWireup="true"
    CodeFile="~/Default.aspx.cs" Inherits="Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
</asp:Content>

Namespaces

C#

using System.Data;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;

VB.Net

Imports System.Data.SqlClient
Imports System.Data
Imports System.IO

Code

MasterPage.aspx.cs

public void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem, UserControl userControl = null, Menu menu = null)
{
    UserControl uc = userControl;
    Menu Menu1 = menu;
    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, null, null);
        }
        else
        {
            parentMenuItem.ChildItems.Add(menuItem);
            if (parentMenuId > 0)
            {
                DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
                PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
            }
        }
    }
}

public 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;
    }
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        Site1 master = Master as Site1;
        DataTable dt = master.GetData(0);
        UserControl uc = (UserControl)Master.FindControl("menu");
        Menu menu1 = (Menu)uc.FindControl("Menu1");
        master.PopulateMenu(dt, 0, null, uc, menu1);
    }
}

VB.Net

MasterPage.aspx.vb

Public Sub PopulateMenu(ByVal dt As DataTable, ByVal parentMenuId As Integer, ByVal parentMenuItem As MenuItem, Optional ByVal userControl As UserControl = Nothing, Optional ByVal menu As Menu = Nothing)
    Dim uc As UserControl = userControl
    Dim Menu1 As Menu = menu
    Dim currentPage As String = Path.GetFileName(Request.Url.AbsolutePath)
    For Each row As DataRow In dt.Rows
        Dim menuItem As MenuItem = 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, Nothing, Nothing)
        Else
            parentMenuItem.ChildItems.Add(menuItem)
            If parentMenuId > 0 Then
                Dim dtChild As DataTable = Me.GetData(Integer.Parse(menuItem.Value))
                PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
            End If
        End If
    Next
End Sub

Public Function GetData(ByVal 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 SqlConnection = New SqlConnection(constr)
        Dim dt As DataTable = New DataTable()
        Using cmd As SqlCommand = New SqlCommand(query)
            Using sda As SqlDataAdapter = 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

Default.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim master1 As Sit2 = TryCast(Master, Sit2)
        Dim dt As DataTable = master1.GetData(0)
        Dim uc As UserControl = CType(master.FindControl("menu"), UserControl)
        Dim menu1 As Menu = CType(uc.FindControl("Menu1"), Menu)
        master1.PopulateMenu(dt, 0, Nothing, uc, menu1)
    End If
End Sub

Screenshot