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

About these ads

27 Responses to “How to bind asp.net menu control with database ?”

  1. Talha Ashfaque Says:

    i have 2 similar post regarding hierarchical data display:

    http://www.codeshode.com/2011/07/display-hierarchical-data-with-menu.html

    http://www.codeshode.com/2010/05/display-hierarchical-data-with-treeview.html

    http://www.codeshode.com/2010/06/display-directory-structure-using.html

    • Chandra Dev Says:

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

  2. Rohit Kale Says:

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

  3. Chandra Dev Says:

    You are welcome.

  4. kishore Says:

    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 Says:

      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

  5. Manish Srivastava Says:

    Thanks Alot

  6. Manish Srivastava Says:

    Post to how we navigate to another Page

  7. Chandra Dev Says:

    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 Says:

      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 Says:

        Please give me some time to check the code.

    • lakshmikanthreddy Says:

      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

  8. deepa Says:

    Thanks a lot.really very useful

  9. sri Says:

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

  10. Chandra Dev Says:

    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 ?

  11. aslam Says:

    thks for the help

  12. thirureka Says:

    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…

  13. thirureka Says:

    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…

  14. lakshmikanthreddy Says:

    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 Says:

      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

  15. thigireddy Says:

    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 Says:

      HI

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

  16. Yusuf Mansuri Says:

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

    }

    }

  17. layneripley Says:

    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?

  18. [RESOLVED]Creating Multilevel Menu at Runtime in ASP.NET? | ASP.NET MVC Says:

    […] http://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/ […]

  19. [RESOLVED]Populating HTML Menu Recursively | ASP Web Form Data Control Says:

    […] you need to follow something like this – http://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/&nbsp; […]

  20. ebookreader Says:

    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!


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 )

Google+ photo

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

Connecting to %s

Software Engineering

.NET, SQL and Mobile

Darren's Blog

.NET, MVC

Prashant Brall's Blog

Every idea is a great idea as long as it is simple.

Code Wala

Designing and coding

Ambilykk's Blog

My learning bites in Different Technologies

DOT NET RULES

Yes, to dance beneath the diamond sky with one hand waving free

Matt Duffield

One developer to another...

debugmode

debugging Learning

ASP.NET

Just another WordPress.com weblog

Ramani Sandeep's Blog

DotNetting - Fast , Easy Way of Developing Applications

Mehroz's Experiments

My computational experiments, mostly related to .Net and SQL server, to be posted here

Max Vergelli /// dev.blog

Personal code repository of Max Vergelli, web designer and software developer.

Ramblings of the Sleepy...

For an underpaid web architect and overplayed gamer... there is no such thing as sleep.

Code Simplified - Viral Sarvaiya

Code Simplified - Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Sharker Khaleed Mahmud Silverlight Tips & Tricks

Either write something worth reading or do something worth writing

DotNet Strings

.Net Development

Follow

Get every new post delivered to your Inbox.

Join 51 other followers

%d bloggers like this: