Creating Dynamic Menus and Submenus in an ASP.NET Website

Introduction

Having a menu and sub menus with links is very normal in a Web application. Typically, we create static menu and menu items. But sometimes we need dynamic menus when we do not know what the menu names and links will be called.

In this article, we will see how to create dynamic menu and sub menus in an ASP.NET application.

Mainly in CMS application we require to customary web layout, Menu and Submenu Items. In this article, you learn how to dynamically add Menu and Sub Menu Links for our Web Application.

Step 1: Create Database say (Database.mdf)

Add 2 tables to the database - MainMenu and SubMenu. The table design looks like the following:

Menus1.gif

Step 2: add ConnectionString in web.config. as given below.
  1. <connectionStrings>  
  2. <add name="ConnectionString" connectionString="Data Source=.; AttachDbFilename= DynamicallyControlCreationOfMenuSubmenuItems \App_Data\Database.mdf;User ID=**;Password=*****;Pooling=False" providerName=".NET Framework Data Provider for SQL Server"/>  
  3. </connectionStrings>  
Step 3: Open Visual Studio 2005/2008->File->New Website

Menus2.gif

Step 4: Open Solution Explorer ->Add New item

Add CreateMenu.aspx

Menus3.gif

Step 5: Design the page and Place required Controls in it. As you can see from this design, a user can enter a Menu name, content, order and activate it. Same applies to the sub menu except the fact that user will have to select a main menu. 

Menus4.gif

Menus5.gif

Step 6: Add Main Menu Items by double click on submit Button -> Now write the below code.
  1. protected void btnMainmenu_Click(object sender, EventArgs e)  
  2. {  
  3.     int active;  
  4.     if (chkMActive.Checked)  
  5.     {  
  6.         active = 1;  
  7.     }  
  8.     else  
  9.     {  
  10.         active = 0;  
  11.     }  
  12.     SqlConnection conn = new SqlConnection(connection);  
  13.     string sql = "INSERT INTO MainMenu(MainMenu, MContent, MenuOrder,  IsActive)VALUES('" + txtMainmenu.Text + "','" + txtMContent.Text + "'," + Convert.ToInt16(ddlMOrder.SelectedItem.Value) + "," + active + ")";  
  14.     SqlCommand cmd = new SqlCommand(sql, conn);  
  15.     conn.Open();  
  16.     cmd.CommandType = CommandType.Text;  
  17.     cmd.ExecuteNonQuery();  
  18.     conn.Close();  
  19.     FillddlMainMenu();  
  20.     Response.Redirect("SuccessMsg.aspx");  
  21. }  
Step 7: Adding Submenus Items.
  1. For this we first need to populate dropdown of Main Menu. Below is the code.
    1. protected void Page_Load(object sender, EventArgs e)  
    2. {  
    3.     if (!IsPostBack)  
    4.     {  
    5.         FillddlMainMenu();  
    6.     }  
    7. }  
    8.   
    9. public void FillddlMainMenu()  
    10. {  
    11.     SqlConnection conn = new SqlConnection(connection);  
    12.     DataSet DS = new DataSet();  
    13.     SqlDataAdapter dataadapter = new SqlDataAdapter();  
    14.     SqlCommand cmd = new SqlCommand("Select MainMenuId,MainMenu from  MainMenu", conn);  
    15.     //cmd.CommandType = CommandType.Text;  
    16.     dataadapter.SelectCommand = cmd;  
    17.     dataadapter.Fill(DS);  
    18.     ddlMainMenu.DataSource = DS;  
    19.     ddlMainMenu.DataBind();  
    20. }
  2. Double click on submit Button -> Now write the below code.
    1. protected void btnSubmenu_Click(object sender, EventArgs e)  
    2. {  
    3.     int active;  
    4.     if (chkSActive.Checked)  
    5.     {  
    6.         active = 1;  
    7.     }  
    8.     else  
    9.     {  
    10.         active = 0;  
    11.     }  
    12.     SqlConnection conn = new SqlConnection(connection);  
    13.     string sql = "INSERT INTO SubMenu(SubMenu, Content, MenuOrder,ParentId, IsActive)VALUES('" + txtSubmenu.Text + "','" + txtSContent.Text + "'," + Convert.ToInt16(ddlSOrder.SelectedItem.Value) + "," + Convert.ToInt16(ddlMainMenu.SelectedItem.Value) + "," + active + ")";  
    14.     SqlCommand cmd = new SqlCommand(sql, conn);  
    15.     conn.Open();  
    16.     cmd.CommandType = CommandType.Text;  
    17.     cmd.ExecuteNonQuery();  
    18.     conn.Close();  
    19.     Response.Redirect("SuccessMsg.aspx");  
    20. }

Step 8: Now to Show Menu Items we need to add another page. Add 2 Data lists for Main Menu(Horizontally) Submenus Items(Vertically).  

Menus6.gif

Step 9: Now Write Code for populating Main Menu Items in datalist to show as menuBar.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     FillMenu();  
  4. }  
  5.   
  6. public void FillMenu()  
  7. {  
  8.     DataSet ds = new DataSet();  
  9.     SqlConnection conn = new SqlConnection(connection);  
  10.     SqlDataAdapter dataadapter = new SqlDataAdapter();  
  11.     SqlCommand cmd = new SqlCommand("Select * from MainMenu ORDER BY  MenuOrder", conn);  
  12.   
  13.     //cmd.CommandType = CommandType.Text;  
  14.     dataadapter.SelectCommand = cmd;  
  15.     dataadapter.Fill(ds);  
  16.     return ds;  
  17.     dlSubMenu.DataSource = ds1;  
  18.     dlSubMenu.DataBind();  
  19. }  
Description: Above code will help to show main menu items as the page loads.

Now we need to populate submenus on selected mainmenu link. We will write code on datalist ItemCommand event.

Step 10: datalist ->Properties ->Add ItemCommand Event.

  1. protected void dlMenu_ItemCommand(object source, DataListCommandEventArgs e)  
  2.   
  3. {  
  4.     LinkButton lnkLink = e.Item.FindControl("lnkLink"as LinkButton;  
  5.     Label lblPageId = e.Item.FindControl("lblpageId"as Label;  
  6.     Session["Sublink"] = lblPageId.Text;  
  7.     if (lnkLink.Text != null)  
  8.   
  9.     {  
  10.         Session["Choice"] = "Main";  
  11.   
  12.         DataSet ds1 = new DataSet();  
  13.         SqlConnection conn = new SqlConnection(connection);  
  14.         SqlDataAdapter dataadapter = new SqlDataAdapter();  
  15.         SqlCommand cmd = new SqlCommand("Select * from SubMenu where IsActive=1 and ParentId='" + Convert.ToInt16(lblPageId.Text) + "' ORDER BY MenuOrder", conn);  
  16.         dataadapter.SelectCommand = cmd;  
  17.         dataadapter.Fill(ds1);  
  18.   
  19.         dlSubMenu.DataSource = ds1;  
  20.         dlSubMenu.DataBind();  
  21.   
  22.     }  
  23. } 

Step 11: Run application (Press F5).

Summary

The Final Layouts Will be as given Below.

Menus7.gif

Menus8.gif

Menus9.gif

Menus10.gif

Summary 

In this article, we discussed how to create a Web site with dynamic menus. The menus and related links were stored in a database and the menus were created at run-time by reading values from the database.


Similar Articles