How to bind asp.net menu control with database ?



Hi
While working on asp.net project, we will get situation to create a dynamic menu control which will be configurable by admin.

For doing this task we can do like this

Step1: I have created a table like this Img

Step2: Configure the asp.net menu control like this

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
<title></title>

<style type="text/css">

.menuItem
{
border:Solid 1px black;
width:100px;
padding:2px;
background-color:#eeeeee;
}
.menuItem a
{
color:blue;
}

.IE8Fix
{
z-index: 1000;

}

</style>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu
id="Menu1"
Orientation="horizontal"
StaticMenuItemStyle-CssClass="menuItem"
DynamicMenuItemStyle-CssClass="menuItem"
Runat="server">
<%– This CSS used for fixing the browser problem with IE8–%>
<DynamicMenuStyle CssClass="IE8Fix" />

</asp:Menu>

</div>
</form>
</body>
</html>

Step3: Write the code for binding asp.net menu on basis of category like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{

populateMenuItem();
}
}

private void populateMenuItem()
{

DataTable menuData = GetMenuData();
AddTopMenuItems(menuData);

}

private DataTable GetMenuData()
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id,ParentId,Name FROM tblProduct", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

}
}

/// Filter the data to get only the rows that have a
/// null ParentID (This will come on the top-level menu items)

private void AddTopMenuItems(DataTable menuData)
{
DataView view = new DataView(menuData);
view.RowFilter = "ParentID IS NULL";
foreach (DataRowView row in view)
{
MenuItem newMenuItem = new MenuItem(row["Name"].ToString(), row["Id"].ToString());
Menu1.Items.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}

}

//This code is used to recursively add child menu items by filtering by ParentID

private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem)
{
DataView view = new DataView(menuData);
view.RowFilter = "ParentID=" + parentMenuItem.Value;
foreach (DataRowView row in view)
{
MenuItem newMenuItem = new MenuItem(row["Name"].ToString(), row["Id"].ToString());
parentMenuItem.ChildItems.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}
}

}

You can download the source code from here
Dynamic Menu

Advertisement

28 thoughts on “How to bind asp.net menu control with database ?

    • Chandra Dev July 21, 2011 / 8:42 am

      Hi
      I saw your post. It is really nice and useful. Thanks for sharing the nice URL.

  1. Rohit Kale November 4, 2011 / 10:36 am

    Great And Nice… Thanks A LOT….!!!!

  2. kishore December 22, 2011 / 6:26 am

    Its really nice post, Could you please tel me code to navigate to another pages (I mean if we click on India (child node), redirects to India.aspx page)

    • Chandra Dev December 23, 2011 / 5:18 am

      Hi
      I glad to know that you liked it. That is also possible like this

      protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
      {
      string name = Menu1.SelectedItem.Text;
      string pageurl=name+”.aspx”;
      Response.Redirect(pageurl);
      }

      Regards
      Chandradev

  3. Chandra Dev January 29, 2012 / 6:37 pm

    Sorry for the late reply. You click on “MenuItemClick” event and write this code. Then it will go to particular page

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
    string name = Menu1.SelectedItem.Text;
    string pageurl=name+”.aspx”;
    Response.Redirect(pageurl);
    }

    • Prasad May 29, 2012 / 7:08 am

      I am not able to get click event of second menu item & its sub items..
      MenuItemClick event is working fine for first menu & its sub menus but not working for the rest..

      • Chandra Dev May 31, 2012 / 2:07 pm

        Please give me some time to check the code.

    • lakshmikanthreddy February 5, 2013 / 5:17 pm

      hi sir , i have completed all the navigation part also but only problem is firstly menuitem.click is not happened and another thing is when menu item is click the content of the lastmenu is displaying for this am sending all my code to plz solve my problem that to in dynamically

  4. deepa June 21, 2012 / 12:16 pm

    Thanks a lot.really very useful

  5. sri September 30, 2012 / 12:36 pm

    My menu is over loaded by the page. How to get the menu on the top of the page?

  6. Chandra Dev October 1, 2012 / 5:41 am

    Hi, could you explain your problem little bit more ? I didnot get you. You means your sub menu is so lenghly . do You want to see it on top ?

  7. aslam November 28, 2012 / 2:29 pm

    thks for the help

  8. thirureka January 30, 2013 / 5:25 am

    Ther eis no error in yor code but i am not getting child node , i can view Menus only
    for example, Country Name and State name
    iits coming But i amnot getting that india and Nepal ( used Your same Code)
    and More thing i want to add image near menus…

  9. thirureka January 30, 2013 / 5:27 am

    There is no error in your code. but i am not getting child menus, i can view Menus only
    for example, Country Name and State name is coming But i am not getting that india and Nepal ( used Your same Code)
    and one More thing i want to add image near menus…

  10. lakshmikanthreddy February 5, 2013 / 5:21 pm

    lakshmikanthreddy :
    hi sir , i have completed all the navigation part also but only problem is firstly menuitem.click is not happened and another thing is when menu item is click the content of the lastmenu is displaying for this am sending all my code to plz solve my problem that to in dynamically
    public partial class menu : System.Web.UI.Page
    {

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    PopulateMenu();

    }
    DataSet GetMenuData()
    {
    SqlConnection con = new SqlConnection(“Data Source=localhost;Initial Catalog=newdata23;User ID=sa;Password=123”);
    SqlDataAdapter dadCats = new SqlDataAdapter(“SELECT cms_title,cms_content FROM cms where status='” + “Active” + “‘ order by priority asc”, con);
    //SqlDataAdapter dadProducts = new SqlDataAdapter(“SELECT * FROM Products”, con);
    DataSet dst = new DataSet();
    dadCats.Fill(dst, “cms”);
    //dadProducts.Fill(dst, “Products”);
    //dst.Relations.Add(“Children”,
    //dst.Tables[“Ca”].Columns[“CategoryID”],
    //dst.Tables[“Products”].Columns[“CategoryID”]);
    return dst;
    }
    int i = 0;
    public void PopulateMenu()
    {
    DataTable dt = new DataTable();
    DataSet dst = GetMenuData();
    foreach (DataRow masterRow in dst.Tables[“cms”].Rows)
    {
    MenuItem masterItem = new MenuItem((string)masterRow[“cms_title”]);
    Menu1.Items.Add(masterItem);
    dt = dst.Tables[“cms”];
    Session[“abc”] = dt.Rows[i][0].ToString();
    masterItem.NavigateUrl = dt.Rows[i][0].ToString() + “.aspx”;
    i++;

    }

    Menu1.DataBind();
    }

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {

    }

    }
    give reply as soon as possible

    • thigireddy February 5, 2013 / 5:25 pm

      thigireddy :

      thigireddy :
      hi sir , i have completed all the navigation part also but only problem is firstly menuitem.click is not happened and another thing is when menu item is click the content of the lastmenu is displaying for this am sending all my code to plz solve my problem that to in dynamically. just add one more coloumn to your database table by the name content i want retrive that that content when menu is clicked
      public partial class menu :
      System.Web.UI.Page
      {
      protected void Page_Load(object sender, EventArgs e)
      {
      if (!IsPostBack)
      PopulateMenu();
      }
      DataSet GetMenuData()
      {
      SqlConnection con = new SqlConnection(“Data Source=localhost;Initial Catalog=newdata23;User ID=sa;Password=123″);
      SqlDataAdapter dadCats = new SqlDataAdapter(“SELECT cms_title,cms_content FROM cms where status=’” + “Active” + “‘ order by priority asc”, con);
      //SqlDataAdapter dadProducts = new SqlDataAdapter(“SELECT * FROM Products”, con);
      DataSet dst = new DataSet();
      dadCats.Fill(dst, “cms”);
      //dadProducts.Fill(dst, “Products”);
      //dst.Relations.Add(“Children”,
      //dst.Tables[“Ca”].Columns[“CategoryID”],
      //dst.Tables[“Products”].Columns[“CategoryID”]);
      return dst;
      }
      int i = 0;
      public void PopulateMenu()
      {
      DataTable dt = new DataTable();
      DataSet dst = GetMenuData();
      foreach (DataRow masterRow in dst.Tables[“cms”].Rows)
      {
      MenuItem masterItem = new MenuItem((string)masterRow[“cms_title”]);
      Menu1.Items.Add(masterItem);
      dt = dst.Tables[“cms”];
      Session[“abc”] = dt.Rows[i][0].ToString();
      masterItem.NavigateUrl = dt.Rows[i][0].ToString() + “.aspx”;
      i++;
      }
      Menu1.DataBind();
      }
      protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
      {
      }
      }
      give reply as soon as possible

  11. thigireddy February 5, 2013 / 5:26 pm

    thigireddy :

    thigireddy :

    thigireddy :
    hi sir , i have completed all the navigation part also but only problem is firstly menuitem.click is not happened and another thing is when menu item is click the content of the lastmenu is displaying for this am sending all my code to plz solve my problem that to in dynamically. just add one more coloumn to your database table by the name content i want retrive that that content when menu is clicked
    public partial class menu :
    System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    PopulateMenu();
    }
    DataSet GetMenuData()
    {
    SqlConnection con = new SqlConnection(“Data Source=localhost;Initial Catalog=newdata23;User ID=sa;Password=123″);
    SqlDataAdapter dadCats = new SqlDataAdapter(“SELECT cms_title,cms_content FROM cms where status=’” + “Active” + “‘ order by priority asc”, con);
    //SqlDataAdapter dadProducts = new SqlDataAdapter(“SELECT * FROM Products”, con);
    DataSet dst = new DataSet();
    dadCats.Fill(dst, “cms”);
    //dadProducts.Fill(dst, “Products”);
    //dst.Relations.Add(“Children”,
    //dst.Tables[“Ca”].Columns[“CategoryID”],
    //dst.Tables[“Products”].Columns[“CategoryID”]);
    return dst;
    }
    int i = 0;
    public void PopulateMenu()
    {
    DataTable dt = new DataTable();
    DataSet dst = GetMenuData();
    foreach (DataRow masterRow in dst.Tables[“cms”].Rows)
    {
    MenuItem masterItem = new MenuItem((string)masterRow[“cms_title”]);
    Menu1.Items.Add(masterItem);
    dt = dst.Tables[“cms”];
    Session[“abc”] = dt.Rows[i][0].ToString();
    masterItem.NavigateUrl = dt.Rows[i][0].ToString() + “.aspx”;
    i++;
    }
    Menu1.DataBind();
    }
    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
    }
    }
    give reply as soon as possible

    • Chandra Dev May 26, 2013 / 11:55 am

      HI

      Sorry for late reply. I m not getting any problem. I have uploaded the code. Please check it.

  12. Yusuf Mansuri June 13, 2013 / 12:14 pm

    Hello sir…

    Your code is really very helpfull…

    Jst do the more needful…

    I have created the menu ,submenu…The only problem is i m unable to do navigation on the click of any sub menu or sub submenu items…

    I also wanted that if user click on any of the menu….I should get the ID of that particular menu and sub menu..

    Pls help me ASAP..

    HERE IS MY CODE

    private void populateMenuItem()
    {
    DataTable menuData = GetMenuData();
    AddTopMenuItems(menuData);
    }

    private DataTable GetMenuData()
    {

    System.Data.OleDb.OleDbConnection conn = new OleDbConnection(strConn);

    string strSqlQuery = “SELECT MenuID,MenuName,Handler,ParentID FROM Mainmenu”;

    System.Data.OleDb.OleDbCommand cmd = new OleDbCommand(strSqlQuery, conn);

    System.Data.OleDb.OleDbDataAdapter objDA = new OleDbDataAdapter(cmd);

    DataTable dt = new DataTable();

    objDA.Fill(dt);

    return dt;

    }
    /// Filter the data to get only the rows that have a
    /// null ParentID (This will come on the top-level menu items)
    private void AddTopMenuItems(DataTable menuData)
    {
    DataView view = new DataView(menuData);
    view.RowFilter = “ParentID = 0”;

    foreach (DataRowView row in view)
    {
    MenuItem newMenuItem = new MenuItem(row[“MenuName”].ToString(), row[“MenuID”].ToString(), row[“Handler”].ToString());
    Menu1.Items.Add(newMenuItem);
    AddChildMenuItems(menuData, newMenuItem);

    }

    }

    ///This code is used to recursively add child menu items by filtering by ParentID
    private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem)
    {
    DataView view = new DataView(menuData);
    view.RowFilter = “ParentID=” + parentMenuItem.Value;
    foreach (DataRowView row in view)
    {
    MenuItem newMenuItem = new MenuItem(row[“MenuName”].ToString(), row[“MenuID”].ToString());

    parentMenuItem.ChildItems.Add(newMenuItem);
    AddChildMenuItems(menuData, newMenuItem);

    for (int i = 0; i < view.Count; i++)
    {
    int iRowCount = view.ToTable(true, "MenuID").Rows.Count;
    }

    }

    }

  13. layneripley August 15, 2013 / 3:51 pm

    I occasionally publish commentary, nonetheless I looked through a
    huge amount of responses here on How to bind asp.
    net menu control with database ? | Chandradev’s Blog but had a couple of thoughts for you if you wouldn’t
    mind. Could it be just me or do quite a few of the above remarks seem to be as if they are provided
    by really dumb persons? Also, when you’re posting on other various internet pages, I’d
    like to stay in touch with you. Might you post a listing of
    all of your social network sites such as your linkedin user profile, Facebook page
    or twitter feed?

  14. ebookreader September 7, 2014 / 11:58 am

    Hi there, I found your site by the use of Google while looking
    for a similar subject, your website came up, it appears good.
    I have bookmarked it in my google bookmarks.
    Hi there, simply changed into aware of your blog thru Google, and located that it is really informative.
    I am gonna watch out for brussels. I’ll appreciate in the event you proceed this
    in future. Numerous other folks will likely be benefited out of your writing.
    Cheers!

  15. DanielCole November 2, 2014 / 3:46 pm

    Nice post )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.