In all websites we have menus of some type or
other. Here we will talk about creating a hierarchical menu using ASP.NET
MenuItem.
Add a MenuItem control to the page as shown below
<form id="frmMain" runat="server">
<div>
<asp:Menu ID="menuHotels"
runat="server"
onmenuitemclick="menuHotels_MenuItemClick">
</asp:Menu>
</div>
</form>
Code
in code behind page: As this is a sample
application please ignore hard coding of connectionstring and naming
convention.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace Hotels
{
public partial class HotelWorld :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
PopulateMenu();
}
public void
PopulateMenu()
{
DataSet
dst = GetMenuData();
foreach (DataRow
mchildRow in dst.Tables["Countries"].Rows)
{
MenuItem mchildItem = new MenuItem((string)mchildRow["name"],
mchildRow["CountryID"].ToString());
menuHotels.Items.Add(mchildItem);
foreach (DataRow
childRow in mchildRow.GetChildRows("Children"))
{
MenuItem childItem = new MenuItem((string)childRow["name"],
childRow["CityID"].ToString());
mchildItem.ChildItems.Add(childItem);
foreach (DataRow
Child1row in childRow.GetChildRows("Children1"))
{
MenuItem children1Item = new MenuItem((string)Child1row["name"], Child1row["HotelID"].ToString());
childItem.ChildItems.Add(children1Item);
}
}
}
}
DataSet GetMenuData()
{
SqlConnection con = new
SqlConnection(@"Data
Source=Server\MSSQLFULL;Initial Catalog=poc;Integrated Security=True");
SqlDataAdapter dad1 = new
SqlDataAdapter("SELECT
* FROM Countries order by name", con);
SqlDataAdapter dad2 = new
SqlDataAdapter("SELECT
* FROM Cities order by name", con);
SqlDataAdapter dad3 = new
SqlDataAdapter("SELECT
* FROM Hotels order by name", con);
DataSet dst = new DataSet();
dad1.Fill(dst, "Countries");
dad2.Fill(dst, "Cities");
dad3.Fill(dst, "Hotels");
dst.Relations.Add("Children",
dst.Tables["Countries"].Columns["CountryID"], dst.Tables["Cities"].Columns["CountryID"]);
dst.Relations.Add("Children1", dst.Tables["Cities"].Columns["CityID"], dst.Tables["Hotels"].Columns["CityID"]);
return dst;
}
protected void
menuHotels_MenuItemClick(object sender, MenuEventArgs e)
{
Session["menuArgs"] = e;
Session["SelectedCity"]
= e.Item.Value;
Response.Redirect("~/Cities.aspx");
}
}
}
MenuItem control can have child
controls and in this case we have another MenuItem control as its child. We are reading data from database and
assigning Text and Value to menuitem object and then we are adding that object
as a child to the parent MenuItem.
Comments
Post a Comment