27-Mar-2014 0 Comments paras

Recursion can be a bit tricky to master, however comes handy in many situations. One very common and popular use is to build treeview structure. Here is a very simple approach of building a treeivew recursively in C#. Before we jump into recursion we need to realize the specific style to store the data, here is the sample I have used. It uses a "ParentID" to determine whose child it is and this makes it possible to build a tree view to "n" levels of depth.

public class CategoryInfo
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public int ParentID { get; set; }
    public static List Get()
        return new List() {
            new CategoryInfo{CategoryID=1,CategoryName="Food",ParentID=0},
            new CategoryInfo{CategoryID=2,CategoryName="Drinks",ParentID=0},
            new CategoryInfo{CategoryID=3,CategoryName="Accomodation",ParentID=0},
            new CategoryInfo{CategoryID=4,CategoryName="Buffet",ParentID=1},
            new CategoryInfo{CategoryID=5,CategoryName="Plate System",ParentID=1},
            new CategoryInfo{CategoryID=6,CategoryName="Soft Drinks",ParentID=2},
            new CategoryInfo{CategoryID=7,CategoryName="Hard Drinks",ParentID=2},
            new CategoryInfo{CategoryID=8,CategoryName="Whisky",ParentID=7},
            new CategoryInfo{CategoryID=9,CategoryName="Vodka",ParentID=7},

In the front end I have added a Literal "ltrCategory". The implementation to build the tree view recursively is given below.

protected void Page_Load(object sender, EventArgs e)
        List lstCat = CategoryInfo.Get();       
    "; DrawTree(lstCat, 0); ltrCategory.Text += "
"; } public void DrawTree(List lstCat, int CategoryID) { foreach(CategoryInfo cat in lstCat) { if (cat.ParentID == CategoryID) { ltrCategory.Text += "
  • " + cat.CategoryName; if (HasChild(lstCat, cat.CategoryID)) { ltrCategory.Text += "
      "; DrawTree(lstCat, cat.CategoryID); ltrCategory.Text += "
  • "; } } } } public bool HasChild(List lstCat, int CategoryID) { int Count = (from p in lstCat where p.ParentID == CategoryID select p).Count(); return Count > 0 ? true : false; }

    This is what the output looks like

    Now we can simply add a jquery plugin to style the tree view and get it into more usable form. There is a plugin called "superfish" based on jquery which will add some and style and animation effects to the ul li markup. The plugin can be downloaded from here . First we need to reference the jquery, css and the js files into our page.


    Now add the class "sf-menu sf-vertical" to the ul that we build from the server side. The style.css that we have added overrides the default style of the plugin. The menu shall look like this after implementing the plugin.

    You can also download the complete project from DOWNLOAD