Search code examples
asp.netsqlc#-4.0drop-down-menu

Creating Multilevel Menu at Runtime in ASP.NET?


I have database Structure like below

TblMenu >>

MenuID, MenuName, LinkPath, MenuDesc, MenuPosition, IsParent, ChildID

I am fetching Items at Runtime at Masterpage and want to display items properly with my desired CSS Class but Only Top Level (all items). Now I want to Display Sub-Menu Items also as dropdown. Kindly suggest a way yo get that with ASP.NET and C#.

-John Bhatt


Solution

  • What I did here is created two methods and used Menu control.

    protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack)
         {
             LoadMenu();
         }
     }   
     
     void LoadMenu()
     {
         DataTable dt = this.GetData(0);
         PopulateMenu(dt, 0, null);    
     }
    
     private DataTable GetData(int ParentMenuItem)
     {
         string query = "SELECT MenuID, MenuItemID,ParentMenuItem,ItemName,MenuURL,MenuRemarks,ItemPosition FROM [MenuItems] WHERE ParentMenuItem = @ParentMenuItem AND Visibility=1 ORDER BY ItemPosition ASC";
         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToCMS"].ConnectionString);
         SqlDataAdapter adp = new SqlDataAdapter(query, con);
         DataTable dt = new DataTable();
         adp.SelectCommand.CommandType = CommandType.Text;
         adp.SelectCommand.Parameters.AddWithValue("@ParentMenuItem", ParentMenuItem);
         try
         {
             adp.Fill(dt);
         }
         catch (Exception ex)
         {
             throw ex;
         }
         return dt;
     }
    
    
     private void PopulateMenu(DataTable dt, int ParentMenuItem, MenuItem parentMenuItem)
     {
         string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
         foreach (DataRow row in dt.Rows)
         {
             MenuItem menuItem = new MenuItem
             {
                 Value = row["MenuItemId"].ToString(),
                 Text = row["ItemName"].ToString(),
                 NavigateUrl = row["MenuURL"].ToString(),                
                 Selected = row["MenuURL"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
             };
    
             if (ParentMenuItem == 0)
             {
                 MainMenu.Items.Add(menuItem);
                 DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
                 PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
             }
             else
             {
                 parentMenuItem.ChildItems.Add(menuItem);
             }
         }
     }