Tags
Dynamic Menu from Database, Populate Dynamic Menu from Database with recursive function, Populate Dynamic Menu with recursive function
Populate Dynamic Menu from Database with recursive function
Problem: Create a Dynamic Menu in ASP.Net from Database table where data store in Foreign key Relations. (Menu Items can be Nested to ant level)
Table Structure
MenuID | ManuName | MasterID |
---|---|---|
1 | System | 0 |
2 | Menu Creation | 1 |
3 | Role Creation | 1 |
4 | Role Management | 1 |
5 | User Creation | 1 |
6 | User Role Management | 1 |
7 | Email Templates | 1 |
8 | Query Analyzer | 1 |
9 | Master | 0 |
10 | Title Master | 9 |
11 | Type of Office Master | 9 |
12 | Dimension Master | 9 |
13 | Source Type Master | 9 |
14 | Source Details Master | 9 |
15 | Payment Master | 9 |
16 | Business Type Manager | 9 |
17 | Area Master | 9 |
18 | Area KeywordsSynonyms | 9 |
39 | Data Entry | 0 |
40 | Entry | 39 |
41 | Content Management | 0 |
42 | Assignment | 41 |
43 | Validation | 41 |
49 | AASheet Master | 9 |
50 | Locality Update | 41 |
Menu Control in .aspx Page::
<asp:Menu id=”mnuMenu” RunAt=”Server” Orientation=”Horizontal”/>
Code in .cs file
private Dataset MenuDS;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Load Data From DataBase
LoadMenuData();
//Bind Menu Items
BuildMenu(mnuMenu.Items, 0);
}
}
private void LoadMenuData()
{
string strConnection = ConfigurationManager.AppSettings[“ConnectionString”];
string strQuery = “Select MenuId,MenuName,MasterId from MenuMaster”;
SqlConnection conMenu = new SqlConnection(strConnection);
SqlDataAdapter dadMenu = new SqlDataAdapter(strQuery,conMenu);
dadMenu.Fill(MenuDS, “MenuMaster”);
}
private void BuildMenu(MenuItemCollection nodes, Int32 IntParent)
{
Int32 ThisID;
String ThisName;
DataRow[] children =
MenuDS.Tables[0].Select
(“MasterId='” + IntParent + “‘”);
//no child nodes, exit function
if (children.Length == 0) return;
foreach (DataRow child in children)
{
// step 1
ThisID = Convert.ToInt32(child.ItemArray[0]);
// step 2
ThisName = Convert.ToString(child.ItemArray[1]);
// step 3
MenuItem NewNode =
new MenuItem(ThisName, ThisID.ToString());
// step 4
nodes.Add(NewNode);
// step 5
BuildMenu(NewNode.ChildItems, ThisID);
}
}
Menu will populate::
System | Master | Data Entry | Content Management |
Menu Creation | Title Master | Entry | Assignment |
Role Creation | Type of Office Master | Validation | |
Role Management | Dimention Master | Locality Update | |
User Creation | Source Type Master | ||
User Role Management | Source Details Master | ||
Email Template | Payment Master | ||
Query Analyzar | Bussimess Type Master | ||
Area Master | |||
Area Keyword Synonum | |||
AA Sheet Master |
Enjoy!