Search code examples
c#asp.netsubmenu

How to create submenus from database?


I have created menus "Home""About Us" on html page, I want submenus of Home and About us from database by c# code. How to do this?


Solution

  • You will need a table in the database to store the MenuItems. Then Place the ASP.NET Menu control in the page:

    <asp:Menu ID="menuBar" runat="server" Orientation="Horizontal" Width="100%">
    </asp:Menu>
    

    And in the code behind:

    DataTable dt = new DataTable();
    //your sql code to fill dt
    DataRow[] drowpar = dt.Select("ParentID=" + 0);
    
    foreach (DataRow dr in drowpar)
    {
        menuBar.Items.Add(new MenuItem(dr["MenuName"].ToString(), 
                dr["MenuID"].ToString(), "", 
                dr["MenuLocation"].ToString()));
    }
    
    foreach (DataRow dr in dt.Select("ParentID >" + 0))
    {
        MenuItem mnu = new MenuItem(dr["MenuName"].ToString(), 
                       dr["MenuID"].ToString(), 
                       "", dr["MenuLocation"].ToString());
        menuBar.FindItem(dr["ParentID"].ToString()).ChildItems.Add(mnu);
    }
    

    Read this article from codeproject may help you.