Friday 12 October 2012

Bind Menu Control With Database In Asp.Net


Hello guys Now Explaining You how you bind menu control in asp.net
with value which coming from database.
Let Consider that you have database contain two table 1st table Contain menu detail they are as follow 1) Menu ID
2)Menu Name
3)Menu Value
4)Navigate URL
5)Parent ID
2nd table is Menuid and userRole Mapping table contain following 1) Menu ID
2) Role

Now As per role you can get the menu Datatable from database by writing query for that lets see we have datatable wchich contain menu information.
now front side we have one menu item control as
 
    
    
  
 

on server side write following code in pageload method
 dtMenu = GetMenu(Session["Role"].ToString()); //this is datatable

//which contain information menu which you want to bind for that userrole
  ShowMenu(NavigationMenu.Items, 0); 

now here is ShowMenu Method


 private void ShowMenu(MenuItemCollection Node, int parentMenuId)
    {
        DataRow []childMenu = dtMenu.Select("ParentId ='" +parentMenuId + "'");
        if (childMenu.Length == 0) return;
        foreach (DataRow child in childMenu)
        {
        string Name = child.ItemArray[0].ToString();
        string url = child.ItemArray[1].ToString();
        string Role = child.ItemArray[2].ToString();
        int MenuId = Convert.ToInt16(child.ItemArray[4]);
        MenuItem menuItem = new MenuItem(Name, MenuId.ToString(), string.Empty, url);
        Node.Add(menuItem);
        ShowMenu(menuItem.ChildItems, MenuId);
        }
    }

Hope this will help you
Thank You
Chetan V.

No comments:

Post a Comment