• 递归加载TreeView


    以前在做目录的时候,每绑定一个节点到数据库里取一条数据,后来当目录特别大的时候,加载半天没反应。

    在项目中,应尽量减少访问数据库的次数,在加载目录的时候,应一次性把所有的目录数据取出来,以减少访问数据库的时间而提高效率。

    有这么一张Category表,里面有些数据:

    获取List<Category>集合

    首先获取根目录 即ParentID为-1,加载到TreeView

     1 private void InitTree()
     2         {
     3             List<Category> list = service.GetCategoryList();
     4             if (list.Count > 0)
     5             {
     6                 //绑定根目录
     7                 Category model = list.Where(a => a.ParentID == -1).FirstOrDefault();
     8                 if (model != null)
     9                 {
    10                     TreeNode root = new TreeNode();
    11                     root.Value = model.CategoryID.ToString();
    12                     root.Text = model.CategoryName;
    13                     tview.Nodes.Add(root);
    14                     //绑定子目录
    15                     AddChildNode(root, model.CategoryID, list);
    16                 }
    17             }
    18         }
    加载根目录

    加载子目录的时候,注意要把子目录加载在上级目录上,而不是绑定到根目录上,否则全部都是根目录了

     1 private void AddChildNode(TreeNode root, int p, List<Category> list)
     2         {
     3             List<Category> listc = list.Where(a => a.ParentID == p).ToList();
     4             //如果有子节点
     5             if (listc.Count > 0)
     6             {
     7                 foreach (Category item in listc)
     8                 {
     9                     TreeNode treec = new TreeNode();
    10                     treec.Value = item.CategoryID.ToString();
    11                     treec.Text = item.CategoryName;
    12                     root.ChildNodes.Add(treec);//tview.Nodes.Add(treec);//错在这里
    13                     //递归绑定子节点
    14                     AddChildNode(treec, item.CategoryID, list);
    15                 }
    16             }
    17             tview.ExpandDepth = 2;
    18         }
    递归加载子目录

    前台放一个TreeView控件即可:

    1 <div>
    2         <asp:TreeView ID="tview" runat="server" ShowLines="True" autopostback="true" ImageSet="XPFileExplorer">
    3                 <SelectedNodeStyle Font-Bold="True" Font-Size="X-Large" ForeColor="Red" />
    4         </asp:TreeView>
    5     </div>
    TreeView控件

  • 相关阅读:
    jQuery事件
    php学习注意事项
    取消php上传2M的限制(windows服务器)
    PHP编程值得注意的细节
    jQuery load()方法特殊用法!
    PHP显示乱码和apache内部编码问题的解决
    定制Apache索引样式
    这么长时间也没有人看看我
    加载php5apache2_2.dll失败的处理方法
    WinXP下的ApachePHPMySQL安装和配置
  • 原文地址:https://www.cnblogs.com/huangzhen22/p/3264193.html
Copyright © 2020-2023  润新知