Click here to Skip to main content
15,881,380 members
Articles / Web Development / ASP.NET

Populating Menu Control in ASP.NET 2.0 - Using Different Data Sources

Rate me:
Please Sign up or sign in to vote.
4.15/5 (40 votes)
7 Oct 20052 min read 585.9K   7.2K   110   47
An article on how to populate the Menu control in ASP.NET 2.0 using different data sources

Introduction

ASP.NET 2.0 is coming at us at a very fast pace. I have to admit that ASP.NET 2.0 is very different from ASP.NET 1.x. From now on, most of the articles that you will see on this site will target ASP.NET 2.0. In this article, I will look into the Menu control. We will look into populating the Menu control using different sources.

What is a Menu Control?

The Menu control is used to display menus. The menu can be displayed vertically or horizontally. Below are two screenshots showing vertical and horizontal menus:

Horizontal Menu

Vertical Menu

For making a menu change its orientation, you just need to change the Orientation property of the Menu control to Horizontal or Vertical.

Now let's see the different approaches to populate a Menu control.

Populating the Menu using SiteMapDataSource

This is the preferred way of populating the Menu control. SiteMapDataSource allows you to read the information from the .sitemap file which is simply an XML file. Let's take a look at the .sitemap file. As you can see in the file below, all you need to do is to assign the values to the nodes and that's it.

XML
<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
 <siteMapNode url="Default.aspx" title="Home">
   <siteMapNode title="Products" description="Our Products">
      <siteMapNode url="Product1.aspx" title="My Products" 
          description="These are my products" />
      <siteMapNode url="Product2.aspx" title="New Products" 
          description="Some new products " />
   </siteMapNode>
   <siteMapNode title="Services" description="Our Services">
      <siteMapNode url="Service1.aspx" title="ASP.NET Consulting"
          description="Best ASP.NET Consulting" />
      <siteMapNode url="Service2.aspx" title="ASP.NET Training" 
          description="Best ASP.NET Training" />
   </siteMapNode>
 </siteMapNode>
</siteMap>

Now let's see how we build our menu using the .sitemap file above. All we are doing in the GetSiteMapDataSource method is getting the information from the Web.sitemap file and building the menu based on the contents of that file.

C#
private void CreateMenuControl()
{
  Menu1.DataSource = GetSiteMapDataSource();
  Menu1.DataBind();
}

private SiteMapDataSource GetSiteMapDataSource()
{
  XmlSiteMapProvider xmlSiteMap = new XmlSiteMapProvider();
  System.Collections.Specialized.NameValueCollection 
         myCollection = new 
         System.Collections.Specialized.NameValueCollection(1);
  myCollection.Add("siteMapFile", "Web.sitemap");
  xmlSiteMap.Initialize("provider", myCollection);
  xmlSiteMap.BuildSiteMap();
  SiteMapDataSource siteMap = new SiteMapDataSource();
  return siteMap;
}

Populating the Menu using the Database

Suppose that you have some data in the database tables using which you want to populate the Menu. Although I prefer the .sitemap technique since that is its sole purpose, the code below shows how you can use database as a data source.

C#
private void PopulateMenu()
{
  DataSet ds = GetDataSetForMenu();
  Menu menu = new Menu();

  foreach (DataRow parentItem in ds.Tables["Categories"].Rows)
  {
    MenuItem categoryItem = new MenuItem((string)parentItem["CategoryName"]);
    menu.Items.Add(categoryItem);

    foreach (DataRow childItem in parentItem.GetChildRows("Children"))
    {
      MenuItem childrenItem = new MenuItem((string)childItem["ProductName"]);
      categoryItem.ChildItems.Add(childrenItem);
    }
  }

  Panel1.Controls.Add(menu);
  Panel1.DataBind();
}

private DataSet GetDataSetForMenu()
{
  SqlConnection myConnection = new SqlConnection(GetConnectionString());
  SqlDataAdapter adCat = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
  SqlDataAdapter adProd = new SqlDataAdapter("SELECT * FROM Products", myConnection);

  DataSet ds = new DataSet();
  adCat.Fill(ds, "Categories");
  adProd.Fill(ds, "Products");
  ds.Relations.Add("Children", 
     ds.Tables["Categories"].Columns["CategoryID"], 
     ds.Tables["Products"].Columns["CategoryID"]);
  return ds;
}

Let's first look at the GetDataSetForMenu() since its being called from PopulateMenu(). In the GetDataSetForMenu() method, we make a relationship between the Categories table and the Products table.

The PopulateMenu() methods receives the DataSet from the GetDataSetForMenu() and iterates through the DataSet. For each iteration, it creates a new MenuItem and adds it into the menu items collection.

Populating the Menu Control Using an XML File

You can also populate the menu using a simple XML file. Check out the code below:

C#
private void CreateMenuWithXmlFile()
{
  string path = @"C:\MyXmlFile.xml";
  DataSet ds = new DataSet();
  ds.ReadXml(path);
  Menu menu = new Menu();
  menu.MenuItemClick += new MenuEventHandler(menu_MenuItemClick);

  for (int i = 0; i < ds.Tables.Count; i++)
  {
    MenuItem parentItem = new MenuItem((string)ds.Tables[i].TableName);
    menu.Items.Add(parentItem);

    for (int c = 0; c < ds.Tables[i].Columns.Count; c++)
    {
      MenuItem column = new MenuItem((string)ds.Tables[i].Columns[c].ColumnName);
      menu.Items.Add(column);

      for (int r = 0; r < ds.Tables[i].Rows.Count; r++)
      {
        MenuItem row = new MenuItem((string)ds.Tables[i].Rows[r][c].ToString());
        parentItem.ChildItems.Add(row);
      }
    }
  }

  Panel1.Controls.Add(menu);
  Panel1.DataBind();
}

I get the XML from the DataSet ReadXML() method. And after that, it's just a matter of iterating through the DataSet and making MenuItems.

I hope you liked the article. The project file is also attached, please download it and run the application.

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
GeneralFull Item Click Pin
tabz_200418-Jan-07 3:10
tabz_200418-Jan-07 3:10 
QuestionSetting HTML properties? Pin
Hameron31-Oct-06 3:15
Hameron31-Oct-06 3:15 
Generalsuperb Pin
Vipin.d9-Oct-06 23:17
Vipin.d9-Oct-06 23:17 
GeneralI want to create three levels menu Pin
MostafaHamdy1-Oct-06 22:43
MostafaHamdy1-Oct-06 22:43 
AnswerRe: I want to create three levels menu Pin
Longhorn2132-Mar-07 10:04
Longhorn2132-Mar-07 10:04 
QuestionReg Menu controls Pin
Coder.8620-Sep-06 18:27
Coder.8620-Sep-06 18:27 
GeneralSame functionality for native c# form app Pin
dodjer4208-Aug-06 16:57
dodjer4208-Aug-06 16:57 
GeneralJAVASCRIPT ON MENU ITEM CLICK Pin
Zapss26-Mar-06 0:03
Zapss26-Mar-06 0:03 
IT IS POSSIBLE TO ADD JAVASCRIPT CODE WHEN MENU ITEM CLICK.
GeneralRe: JAVASCRIPT ON MENU ITEM CLICK Pin
SATNELS2-May-06 6:33
SATNELS2-May-06 6:33 
QuestionRe: JAVASCRIPT ON MENU ITEM CLICK Pin
makarand keer1-Jun-06 5:39
makarand keer1-Jun-06 5:39 
AnswerRe: JAVASCRIPT ON MENU ITEM CLICK Pin
Nate K12-Aug-06 10:45
Nate K12-Aug-06 10:45 
GeneralRe: JAVASCRIPT ON MENU ITEM CLICK Pin
Zapss13-Aug-06 19:46
Zapss13-Aug-06 19:46 
GeneralRe: JAVASCRIPT ON MENU ITEM CLICK Pin
Wouter Spelt28-Feb-07 22:40
Wouter Spelt28-Feb-07 22:40 
QuestionRe: JAVASCRIPT ON MENU ITEM CLICK Pin
VaniRajasekar28-Sep-07 0:38
VaniRajasekar28-Sep-07 0:38 
AnswerRe: JAVASCRIPT ON MENU ITEM CLICK Pin
Wouter Spelt28-Sep-07 1:27
Wouter Spelt28-Sep-07 1:27 
GeneralRe: JAVASCRIPT ON MENU ITEM CLICK Pin
VaniRajasekar28-Sep-07 21:34
VaniRajasekar28-Sep-07 21:34 
QuestionHow do you populate the navigation? Pin
Ritesh Ramesh20-Mar-06 17:36
Ritesh Ramesh20-Mar-06 17:36 
AnswerRe: How do you populate the navigation? Pin
kostaaaaaaa15-Dec-06 22:24
kostaaaaaaa15-Dec-06 22:24 
GeneralGetSiteMapDataSource Pin
Jeffrey Scott Flesher19-Oct-05 14:08
Jeffrey Scott Flesher19-Oct-05 14:08 
GeneralRe: GetSiteMapDataSource Pin
azamsharp19-Oct-05 14:11
azamsharp19-Oct-05 14:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.