开发者

How the generate TreeView in asp.net?

Consider the following table. It has 3 filed with the following data. Now I want to show the data in TreeView Control in asp.net and c# I will select all the data in a DataTable.

category_id category_name   parents_id
1           Root            NUL开发者_如何学CL
2           Teacher         1
3           Student         1
4           TeacherA        2
5           TeacherB        2
6           TeacherC        2
7           StudentA        3
8           StudentB        3
9           StudentC        3


Here are some useful tips for you: for implementing tree view using asp.net and c#

NOte: I did not implement and did not use your datatable data here ....

  • TreeView control expects a heirarchical data structure, so we cant bind the DataTable to menu directly.

  • Use data table Select where ParentID = ID

  • Please use a recursive method to create child items relevent to current menu item ID

  • Here is an working example that you may use to transfer your ralational data structure (TABLE) to hierarchical data structure (TREE) using the relationship between ParentID and ID

    <%@ Page Language="C#" %>
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head id="Head1" runat="server">
       <script runat="server">
    
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (!this.IsPostBack)
            this.AddNodes(this.trvCategories.Nodes, 0, this.LoadData());
    }
    private void AddNodes(TreeNodeCollection nodes, int level, System.Data.DataTable dt)
    {
        string filterExp = string.Format("ParentID='{0}'", level);
        foreach (System.Data.DataRow r in dt.Select(filterExp))
        {
            TreeNode item = new TreeNode()
            {
                Text = r[1].ToString(),
                Value = r[2].ToString()
            };
            this.AddNodes(item.ChildNodes, int.Parse(r[0].ToString()), dt);
            nodes.Add(item);
        }
    }
    private System.Data.DataTable LoadData()
    {
        ///
        /// For the simplicity I do build the datatable dynamically,
        /// But you may get this data from the DATABASE
        ///
        System.Data.DataTable dt = new System.Data.DataTable();
        dt.Columns.Add("ID", String.Empty.GetType());
        dt.Columns.Add("[Name]", String.Empty.GetType());
        dt.Columns.Add("[Value]", String.Empty.GetType());
        dt.Columns.Add("ParentID", String.Empty.GetType());
        dt.Columns.Add("[Order]", String.Empty.GetType());
        int index = 9;
        for (int i = 0; i < 1100; i++)
        {
            string item = "{0},Item{1},Value{1},{2},{1}";
            if (i < 110)
            {
                index = i < 10 ? 0 : int.Parse(Math.Ceiling((decimal)i / 10).ToString());
                dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
            }
            else
            {
                if (i % 10 == 0) index++;
                dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
            }
        }
        return dt;
    }
    


I recently posted some code on Code Review which answers this question. Here it is below, slightly modified for your table. I have tried to meet your needs by using a DataTable as the input, but I haven't used DataTables with LINQ before so you may need to edit slightly.

public TreeNode GenerateCategoriesTree(DataTable dt) {
  var s = new Stack<TreeNodeAndId>();
  var categories = dt.AsEnumerable();
  var rootCategory = categories.Single(o => o.Field<int?>("parents_id") == null);
  var rootNode = new TreeNode(rootCategory["category_name"].ToString(), rootCategory["category_id"].ToString());
  s.Push(new TreeNodeAndId { Id = Convert.ToInt32(rootCategory["category_id"]), TreeNode = rootNode });
  while (s.Count > 0) {
    var node = s.Peek();
    var current = categories.FirstOrDefault(o => o.Field<int?>("parents_id") == node.Id);
    if (current == null) {
      s.Pop();
      continue;
    }
    var child = new TreeNode(current["category_name"].ToString(), current["category_id"].ToString());
    node.TreeNode.ChildNodes.Add(child);
    s.Push(new TreeNodeAndId { Id = Convert.ToInt32(current["category_id"]), TreeNode = child });
    categories.Remove(current);
  }
  return rootNode;
}

struct TreeNodeAndId
{
  public TreeNode TreeNode;
  public int? Id;
}

If this doesn't build then at least I hope it will point you in the right direction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜