Creating Dynamic Menu in ASP.Net

Lakhwinder.ghuman
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 36442 red flag
Rating: 4 out of 5  
 1 vote(s)

Creating Dynamic Menu in ASP.net using the Menu Control by fetching the data from the databse.

Introduction

To create a dynamic menu for the website we would use ASP Menu Control, we can’t bind a Menu control directly to database data. Neither the SqlDataSource nor ObjectDataSource controls implement the IHierachicalDataSource interface. Therefore, if we want to represent database data with the Menu control, we need to perform some more work i.e. build the menu items programmatically in the Menu control. This is the approach followed here.


Imagine that you want to represent the contents of the database table with a


Menu control:

This database table represents menu items. The menu items are nested with the help Of the Parent column. For example, the customer menu item is nested under the User management as shown similarly the further nesting can also be done. 

LISTING 1.1 MenuDatabase.aspx

protected void Page_Load(object sender, EventArgs e)

    {

        #region Page-Load-Code

           

                if (!Page.IsPostBack)

                    PopulateTreeView();

        #endregion

    }

 

    private void PopulateTreeView()

    {

       

        DataTable treeViewData = GetTreeViewData();

        AddTopTreeViewNodes(treeViewData);

    }

 

 

    private DataTable GetTreeViewData()

    {

            // Get Menu table

            string selectCommand = "SELECT Id,Parent,Description FROM MenuBarMaster";

            string conString = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;

            SqlDataAdapter dad = new SqlDataAdapter(selectCommand, conString);

            DataTable dtblDiscuss = new DataTable();

            dad.Fill(dtblDiscuss);

            return dtblDiscuss;

    }

 

    // This will Get Parent elements from the datatable i.e the root values

 

    private void AddTopTreeViewNodes(DataTable treeViewData)

    {

        try

        {

            DataView view = new DataView(treeViewData);

            view.RowFilter = "[Parent] IS NULL";

            foreach (DataRowView row in view)

            {

                TreeNode newNode = new TreeNode(row["Description"].ToString(), row["Id"].ToString());

                TreeView1.Nodes.Add(newNode);

                AddChildTreeViewNodes(treeViewData, newNode);

            }

        }

        catch (Exception ex)

        {

            ScriptManager.RegisterStartupScript(Page, typeof(Page), "dialog""alert('Unexpected Error');"true);

 

        }

    }

 

 

            // Add child Nodes for the menu

 

    private void AddChildTreeViewNodes(DataTable treeViewData, TreeNode parentTreeViewNode)

    {

        try

        {

            DataView view = new DataView(treeViewData);

            view.RowFilter = "[Parent]=" + parentTreeViewNode.Value;

            foreach (DataRowView row in view)

            {

                TreeNode newNode = new TreeNode(row["Description"].ToString(), row["Id"].ToString());

                parentTreeViewNode.ChildNodes.Add(newNode);

                AddChildTreeViewNodes(treeViewData, newNode);

            }

        }

        catch (Exception ex)

        {

            ScriptManager.RegisterStartupScript(Page, typeof(Page), "dialog""alert('Unexpected Error');"true);

 

        }

    }

Now Format Menu Control in .aspx page as shown below:

<asp:Menu ID="Menu1" runat="server" Width="236px" OnMenuItemClick="Menu1_MenuItemClick" Height="99px"><DynamicHoverStyle Font-Bold="True" Font-Names="Verdana" Font-Size="14px"/>                                                          <DynamicMenuItemStyle BackColor="#F3F3F3" BorderColor="#F3F3F3"Font-Names="Verdana"                                                              Font-Size="16px" ItemSpacing="5px" />

<DynamicMenuStyle BorderColor="#F3F3F3" BackColor="#F3F3F3" />

<StaticHoverStyle Font-Names="Verdana" Font-Size="14px" />

<StaticMenuItemStyle Font-Bold="True" Font-Names="Verdana" Font-Size="16px" ItemSpacing="4px" />

<StaticMenuStyle HorizontalPadding="5px" VerticalPadding="10px" />

</asp:Menu>

The menu items are added to the Menu control in the PopulateMenu() method. This

Method first grabs a DataTable that contains the contents of the MenuMaster database table.

Next, it creates a menu item for each row that does not have a parent row (each row Where the Parent column has the value null).The child menu items for each menu item are added recursively. The Parent column is used to filter the contents of the Menu Master DataTable.

Hope this was useful !

Thanks for reading, do let me know your comments or feedback by replying to this article. 

Page copy protected against web site content infringement by Copyscape

About the Author

Lakhwinder.ghuman
Full Name: Lakhwinder Ghuman
Member Level: Starter
Member Status: Member
Member Since: 5/4/2011 7:09:31 AM
Country: India
Best Regards Lakhwinder Ghuman
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: A4u_6178 on: 7/20/2011 | Points: 25
hi Lakhwinder.ghuman,
Is this article article complete or still something are supposed to be added..
Pls go through the article...
Posted by: Malkit on: 3/11/2012 | Points: 25
the table is missing...
this table can be used....
menuId menuDescription menuParentId menuNavigation

1 Administration NULL http://www.google.com
2 Project Management 1 http://www.facebook.com
3 User Management 1 http://www.yahoo.com
4 Account Management NULL http://www.hotmail.com
5 Add New Project 2 http://www.gmail.com


where Administration and Account Management will be added at root, and project management and user management will be added under Administration, whereas add new project will be added under Project management..

Login to post response

Comment using Facebook(Author doesn't get notification)