Asp.net Building Dynamic Menu
Hi everyone! Today we'll build a dynamic site menu with asp.net. To build a dynamic menu we need at least one database table to store categories or menu items. Main items, subitems etc..
I assume that you have a database stores these items in table with "id, name, parent_id" columns. If parent_id is null or zero then we undestrand that is a main item. Else column strores parent id. (main item).
And in this tutorial we have a class named "category". It's an e-commerce tutorial so we need main categories and sub categories in our web site menu. Also we have two methods that returns DataTable in category class named "getAllparents" and "getAllChilds". We list all main items with getAllParents method and all sub items with getAllChilds method in category class.
Now we can start building menu:
protected void generateMenu()
{
category myCategory = new category(); // new category
DataTable mainDt = new DataTable();
mainDt = myCategory.getAllParents(); // we get main items
DataTable childDt = new DataTable();
childDt = myCategory.getAllChilds(); // we get sub items
// now we have to set a relation between main items and sub items.
DataSet ds = new DataSet();
ds.Tables.Add(mainDt);
ds.Tables.Add(childDt);
ds.Relations.Add("Child",ds.Tables[0].Columns["id"], ds.Tables[1].Columns["parent_id"]);
// and finally we have to add these items in asp.net menu controller that we placed on project.
foreach (DataRow mainRow in ds.Tables[0].Rows)
{
MenuItem parentItem = new MenuItem(mainRow["name"].ToString());
parentItem.NavigateUrl = "default.aspx"; // main item navigate url
Menu1.Items.Add(parentItem);
foreach (DataRow childRow in mainRow.GetChildRows("Child"))
{
MenuItem childItem = new MenuItem((string)childRow["name"]);
childItem.NavigateUrl = "view_category.aspx?catId="+childRow["id"];
parentItem.ChildItems.Add(childItem); // sub item navigate url
}
}
I hope it's a useful tutorial about building dynamic menus with asp.net.











