如何编程动态创建 TreeView (WinForms版)

其实动态创建 TreeView/Menu 是再简单不过的一件事了,如果你还记得汉诺塔递归这么一故事,你不应该不知道如何建树,如果你知道MSDN,你也不应该抱怨API不懂得用

放在这里仅仅方便初学者参考而已,大虾可略过 ....

Web 版本见:ASP.NET DEMO 15: 如何编程动态创建 TreeView

using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Linq;
using  System.Text;
using  System.Windows.Forms;
using  System.IO;
using  System.Data.OleDb;

namespace  LeoLab.WinForms.DynamicallyCreateTreeView
{
    
public   partial   class  Form1 : Form
    {
        
public  Form1()
        {
            InitializeComponent();
        }

        
private   void  Form1_Load( object  sender, EventArgs e)
        {
            CreateTreeView();
            CreateMenuStrip();
        }

        
///   <summary>
        
///  创建 TreeView
        
///  此方法采取一次性加载目标数据到 DataTable,递归查询 DataTable ,创建子节点
        
///   </summary>
         private   void  CreateTreeView()
        {
            
//
             const   int  VirtualRootId  =   0 //  虚拟的根节点 ID, 表中 ParentID=0 的节点表示无实际父节点
             const   string  SQL_SELECT  =   " SELECT NodeId, NodeName,ParentId FROM TreeView ORDER BY NodeId ASC " ;

            
//
             string  connStr  =   " Provider=Microsoft.Jet.OleDb.4.0;data source= "   +  Path.Combine(Application.StartupPath,  " TreeViewDemo.mdb " );
            
//
            OleDbDataAdapter da  =   new  OleDbDataAdapter(SQL_SELECT, connStr);
            DataTable dt 
=   new  DataTable();
            
//
            da.Fill(dt);
            
//
            CreateTreeViewRecursive(treeMenu.Nodes, dt, VirtualRootId);
        }

        
///   <summary>
        
///  递归查询数据,创建 TreeNode 节点s
        
///   </summary>
        
///   <param name="nodes"></param>
        
///   <param name="dataSource"></param>
        
///   <param name="parentId"></param>
         private   void  CreateTreeViewRecursive(TreeNodeCollection nodes, DataTable dataSource,  int  parentId)
        {
            
//
             string  fliter  =  String.Format( " ParentId={0} " , parentId);
            
//  查询子节点
            DataRow[] drArr  =  dataSource.Select(fliter);

            TreeNode node;
            
foreach  (DataRow dr  in  drArr)
            {
                
//
                node  =   new  TreeNode();
                nodes.Add(node);
                node.Text 
=  ( string )dr[ " NodeName " ];
                
//  设置其他属性
                
//       

                
//  递归创建子节点
                CreateTreeViewRecursive(node.Nodes, dataSource, ( int )dr[ " NodeId " ]);

                
//  移除已添加行,提高性能
                dataSource.Rows.Remove(dr);
            }
        }

        
///   <summary>
        
///  创建 Menu
        
///  此方法采取一次性加载目标数据到 DataTable,递归查询 DataTable ,创建子节点
        
///   </summary>
         private   void  CreateMenuStrip()
        {
            
//
             const   int  VirtualRootId  =   0 //  虚拟的根节点 ID, 表中 ParentID=0 的节点表示无实际父节点
             const   string  SQL_SELECT  =   " SELECT NodeId, NodeName,ParentId FROM TreeView ORDER BY NodeId ASC " ;

            
//
             string  connStr  =   " Provider=Microsoft.Jet.OleDb.4.0;data source= "   +  Path.Combine(Application.StartupPath,  " TreeViewDemo.mdb " );
            
//
            OleDbDataAdapter da  =   new  OleDbDataAdapter(SQL_SELECT, connStr);
            DataTable dt 
=   new  DataTable();
            
//
            da.Fill(dt);
            
//
            CreateMenuStripRecursive(menuStrip1.Items, dt, VirtualRootId);
        }

        
///   <summary>
        
///  递归查询数据,创建 TreeNode 节点s
        
///   </summary>
        
///   <param name="nodes"></param>
        
///   <param name="dataSource"></param>
        
///   <param name="parentId"></param>
         private   void  CreateMenuStripRecursive(ToolStripItemCollection items, DataTable dataSource,  int  parentId)
        {
            
//
             string  fliter  =  String.Format( " ParentId={0} " , parentId);
            
//  查询子节点
            DataRow[] drArr  =  dataSource.Select(fliter);

            ToolStripMenuItem item;
            
foreach  (DataRow dr  in  drArr)
            {
                
//
                item  =   new  ToolStripMenuItem();                
                items.Add(item);
                item.Text 
=  ( string )dr[ " NodeName " ];
                
//  设置其他属性
                
//       

                
//  递归创建子节点
                CreateMenuStripRecursive(item.DropDownItems, dataSource, ( int )dr[ " NodeId " ]);

                
//  移除已添加行,提高性能
                dataSource.Rows.Remove(dr);
            }
        }
    }
}

 

源码下载 

你可能感兴趣的:(如何编程动态创建 TreeView (WinForms版))