locked
dynamically construct Treeview in asp.net RRS feed

  • Question

  • User-1254474252 posted
    catid   catName          parentId
    1       Root Category       1
    2       Home Appliances     1
    6       fruits              27
    8       Vegetable           27
    9       books               9
    14      furniture           2
    15      fashion             1
    26      Shirts              15
    27      Fruits-Vegitables   1
    28      Electronics         1

    I wish to generate a checkbox tree view from above table  like

    Root Category
       Home Appliances
           furniture
       Fruits-Vegitables
           fruits
           vegetables 
    
    and so on..

    I have written following code but no luck. Here in the code GetDataTable() function returns a data table based on the query we pass

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = objCon.GetDataTable("select catid,catName, parentId from  category## Heading ##");
                this.PopulateTreeView(dt, 0, null);
    }
    
    }
    
    
    private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
        {
            foreach (DataRow row in dtParent.Rows)
            {
                TreeNode child = new TreeNode
                {
                    Text = row["catName"].ToString(),
                    Value = row["catid"].ToString()
                };
                if (parentId == 0)
                {
                    trCategory.Nodes.Add(child);
                    DataTable dtChild =objCon.GetDataTable("select catid,catName, parentId from  category where status=1 and parentId = " + child.Value);
                    PopulateTreeView(dtChild, int.Parse(child.Value), child);
                }
                else
                {
                    treeNode.ChildNodes.Add(child);
                }
            }
        }

    But it generates repeated data items at first level like

    Root Category
       Root Category
       Home Appliances
       Fruits-Vegitables
    Home Appliances
       furniture
    Fruits-Vegitables
        fruits
        vegetables

    Where i went wrong. I have spent some time but couldnt solve it.

    Wednesday, July 29, 2020 6:15 AM

Answers

  • User-1330468790 posted

    Hi sureshsrivaya,

     

    The problem is that you wrongly used the recursion to construct the tree view.

     

    In the method PopulateTreeView, you don't really do the recursion but simply add all the level 2 nodes to the root node.  Apart from that, another problem is that you pass the parentId 0 for the first time so that every data row in the data table will be added in the tree view control.

     

    You could refer to below codes to see how to recursively create the tree view with multiple levels.

    ASPX:

    <form id="form1" runat="server">
            <div>
                <asp:TreeView ID="trCategory" runat="server" ></asp:TreeView>
            </div>
        </form>

    Code behind:

     // Simulation of the data
            private static DataTable _treeviewDT;
            public static DataTable TreeviewDT
            {
                get
                {
                    if (_treeviewDT is null)
                    {
                        _treeviewDT = new DataTable();
    
                        _treeviewDT.Columns.Add("catid", typeof(int));
                        _treeviewDT.Columns.Add("catName", typeof(string));
                        _treeviewDT.Columns.Add("parentId", typeof(int));
    
                        
    
                        _treeviewDT.Rows.Add(1, "Root Category", 0);
                        _treeviewDT.Rows.Add(2, "Home Appliances", 1);
                        _treeviewDT.Rows.Add(6, "fruits", 27);
                        _treeviewDT.Rows.Add(8, "Vegetable", 27);
                        _treeviewDT.Rows.Add(9, "books", 9);
                        _treeviewDT.Rows.Add(14, "furniture", 2);
                        _treeviewDT.Rows.Add(15, "fashion", 1);
                        _treeviewDT.Rows.Add(26, "Shirts", 15);
                        _treeviewDT.Rows.Add(27, "Fruits-Vegitables", 1);
                        _treeviewDT.Rows.Add(28, "Electronics", 1);
    
                    }
    
                    return _treeviewDT;
                }
                set
                {
                    _treeviewDT = value;
                }
            }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    PopulateTreeView();
                }
            }
    
            private void PopulateTreeView()
            {
    
                DataTable root = GetSubCategories(0);
    
                AddChildNodes(root, null);
    
            }
    
            private void AddChildNodes(DataTable categories, TreeNode node)
            {
                foreach (DataRow row in categories.Rows)
                {
                    TreeNode childNode = new TreeNode
                    {
                        Text = row["catName"].ToString(),
                        Value = row["catid"].ToString()
                    };
    
                    if(node == null)
                    {
                        trCategory.Nodes.Add(childNode);
                    }
                    else
                    {
                        node.ChildNodes.Add(childNode);
                    }
    
                    DataTable subCategories = GetSubCategories(Convert.ToInt32(childNode.Value));
                    if (subCategories != null && subCategories.Rows.Count > 0)
                    {
                        AddChildNodes(subCategories, childNode);
                    }
                }
            }
    
    
            private DataTable GetSubCategories(int parentId)
            {
                DataTable dt = null;
                var query = from row in TreeviewDT.AsEnumerable()
                            where row.Field<int>("parentId") == parentId
                            select row;
    
                if (query.Any())
                {
                    dt = query.CopyToDataTable<DataRow>();
                }
                return dt;
            }

    Result Tree View:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 30, 2020 3:39 AM

All replies

  • User-1330468790 posted

    Hi sureshsrivaya,

     

    The problem is that you wrongly used the recursion to construct the tree view.

     

    In the method PopulateTreeView, you don't really do the recursion but simply add all the level 2 nodes to the root node.  Apart from that, another problem is that you pass the parentId 0 for the first time so that every data row in the data table will be added in the tree view control.

     

    You could refer to below codes to see how to recursively create the tree view with multiple levels.

    ASPX:

    <form id="form1" runat="server">
            <div>
                <asp:TreeView ID="trCategory" runat="server" ></asp:TreeView>
            </div>
        </form>

    Code behind:

     // Simulation of the data
            private static DataTable _treeviewDT;
            public static DataTable TreeviewDT
            {
                get
                {
                    if (_treeviewDT is null)
                    {
                        _treeviewDT = new DataTable();
    
                        _treeviewDT.Columns.Add("catid", typeof(int));
                        _treeviewDT.Columns.Add("catName", typeof(string));
                        _treeviewDT.Columns.Add("parentId", typeof(int));
    
                        
    
                        _treeviewDT.Rows.Add(1, "Root Category", 0);
                        _treeviewDT.Rows.Add(2, "Home Appliances", 1);
                        _treeviewDT.Rows.Add(6, "fruits", 27);
                        _treeviewDT.Rows.Add(8, "Vegetable", 27);
                        _treeviewDT.Rows.Add(9, "books", 9);
                        _treeviewDT.Rows.Add(14, "furniture", 2);
                        _treeviewDT.Rows.Add(15, "fashion", 1);
                        _treeviewDT.Rows.Add(26, "Shirts", 15);
                        _treeviewDT.Rows.Add(27, "Fruits-Vegitables", 1);
                        _treeviewDT.Rows.Add(28, "Electronics", 1);
    
                    }
    
                    return _treeviewDT;
                }
                set
                {
                    _treeviewDT = value;
                }
            }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    PopulateTreeView();
                }
            }
    
            private void PopulateTreeView()
            {
    
                DataTable root = GetSubCategories(0);
    
                AddChildNodes(root, null);
    
            }
    
            private void AddChildNodes(DataTable categories, TreeNode node)
            {
                foreach (DataRow row in categories.Rows)
                {
                    TreeNode childNode = new TreeNode
                    {
                        Text = row["catName"].ToString(),
                        Value = row["catid"].ToString()
                    };
    
                    if(node == null)
                    {
                        trCategory.Nodes.Add(childNode);
                    }
                    else
                    {
                        node.ChildNodes.Add(childNode);
                    }
    
                    DataTable subCategories = GetSubCategories(Convert.ToInt32(childNode.Value));
                    if (subCategories != null && subCategories.Rows.Count > 0)
                    {
                        AddChildNodes(subCategories, childNode);
                    }
                }
            }
    
    
            private DataTable GetSubCategories(int parentId)
            {
                DataTable dt = null;
                var query = from row in TreeviewDT.AsEnumerable()
                            where row.Field<int>("parentId") == parentId
                            select row;
    
                if (query.Any())
                {
                    dt = query.CopyToDataTable<DataRow>();
                }
                return dt;
            }

    Result Tree View:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 30, 2020 3:39 AM
  • User-1254474252 posted

    Dear Sean Fang,

    Thank you. You are awesome !

    Thursday, July 30, 2020 7:39 AM
  • User-1254474252 posted

    @sean Fang

    Could you also help me to select a node programatically by its id

    I mean in our example if i wish to select Furniture by its id 14 how can i do that
    And in later stage i may also wish to select more than one node by its id. can u help

    Thursday, July 30, 2020 9:43 AM