Home > Asp.net > How to bind asp.net menu control with database ?

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

}

About these ads
Categories: Asp.net
    • July 21, 2011 at 8:42 am | #2

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

  1. November 4, 2011 at 10:36 am | #3

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

  2. November 4, 2011 at 2:10 pm | #4

    You are welcome.

  3. kishore
    December 22, 2011 at 6:26 am | #5

    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)

    • December 23, 2011 at 5:18 am | #6

      Hi
      I glad to know that you liked it. That is also possible. Please give me some time. I will post the code.

      Regards
      Chandradev

  4. January 17, 2012 at 6:14 am | #7

    Thanks Alot

  5. January 17, 2012 at 6:15 am | #8

    Post to how we navigate to another Page

  6. January 29, 2012 at 6:37 pm | #9

    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 at 7:08 am | #10

      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..

    • lakshmikanthreddy
      February 5, 2013 at 5:17 pm | #12

      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

  7. deepa
    June 21, 2012 at 12:16 pm | #13

    Thanks a lot.really very useful

  8. sri
    September 30, 2012 at 12:36 pm | #14

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

  9. October 1, 2012 at 5:41 am | #15

    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 ?

  10. aslam
    November 28, 2012 at 2:29 pm | #16

    thks for the help

  11. January 30, 2013 at 5:25 am | #17

    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…

  12. January 30, 2013 at 5:27 am | #18

    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…

  13. thigireddy
    February 5, 2013 at 5:26 pm | #19

    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

  1. No trackbacks yet.

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

Follow

Get every new post delivered to your Inbox.

Join 38 other followers

%d bloggers like this: