Monday, November 8, 2010

Hierarchical Data Population

Populating Herarchial data from a table can sometimes get really tricky its not the hardest thing to do but it is something to remember.

The perfict example will be to populate data from a table that has a PK ID a ParentId that shows the which Parent Id the row belongs to and the Name.

In this example I wont be using a SQL Table but a Object List.





Cosider the following




private List<String> menu = new List<String>();
        private List<MenuItem> menuList = new List<MenuItem>();
        private Boolean flag = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadMenu();

            BuildMenu(0);

            foreach (String item in menu)
            {
                litMenu.Text += item;
            }
        }

        private void LoadMenu()
        {
            //List of MenuItem        ID |ParentId  |Name
            //------------------------------------------------------
            menuList.Add(new MenuItem(1,  0,        "Home"));
            menuList.Add(new MenuItem(2,  0,        "Contact Us"));
            menuList.Add(new MenuItem(3,  0,        "About Us"));
            menuList.Add(new MenuItem(4,  1,        "Profile"));
            menuList.Add(new MenuItem(5,  1,        "Goal"));
            menuList.Add(new MenuItem(6,  2,        "Send Mail"));
            menuList.Add(new MenuItem(7,  3,        "What we do"));
            menuList.Add(new MenuItem(8,  7,        "Skinning"));
            menuList.Add(new MenuItem(9,  7,        "Milking"));
            menuList.Add(new MenuItem(10, 3,        "What we wont do"));
        }

        private void BuildMenu(int ParentId)
        {
            List<MenuItem> newList = (from p in menuList
                                      where p.ParentId == ParentId
                                      select p).ToList<MenuItem>();

            if (newList.Count > 0)
            {
                for (int i = 0; i < newList.Count; i++)
                {
                    if (i == 0)
                    {
                            menu.Add("<ul>");
                    }

                    menu.Add("<li>");
                    menu.Add(newList[i].MenuName);
                    BuildMenu(newList[i].ID);
                    menu.Add("</li>");

                    if (i == newList.Count - 1)
                    {
                        menu.Add("</ul>");
                    }

                }
            }
        }
    
The ouput from the object list will be displayed as following
  • Home
    • Profile
    • Goal
  • Contact Us
    • Send Mail
  • About Us
    • What we do
      • Skinning
      • Milking
    • What we wont do
Source Code

No comments:

Post a Comment