动态加载树
陈根发
命题:从数据库读取字段值作为树的节点
实现:
一.把字段值取出放到DataSet 中
二.添加一个根节点
三.添加相应的子节点
代码如下
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace WindowsApplication3
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TreeView treeView1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.treeView1 = new System.Windows.Forms.TreeView();
this.SuspendLayout();
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.treeView1.ImageIndex = -1;
this.treeView1.Location = new System.Drawing.Point(0, 137);
this.treeView1.Name = "treeView1";
this.treeView1.SelectedImageIndex = -1;
this.treeView1.Size = new System.Drawing.Size(352, 136);
this.treeView1.TabIndex = 0;
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(352, 273);
this.Controls.Add(this.treeView1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
}
private void Form1_Load(object sender, System.EventArgs e)
{
ShowForm();
}
private void ShowForm ()
{
treeView1.Nodes.Clear() ;
System.Windows.Forms.TreeNode mNode=new TreeNode("全部");
//mNode.ImageIndex =1;
treeView1.Nodes.Add(mNode) ;
//假设DataSet 已经取得
System.Windows.Forms.TreeNode nNode=new TreeNode("在职");
System.Windows.Forms.TreeNode pNode=new TreeNode("离职");
treeView1.TopNode.Nodes.Add(nNode) ;
treeView1.TopNode.Nodes.Add(pNode) ;
treeView1.Select ();
if (ds.Tables [0].Rows.Count <=0 )
{
return;
}
else
{
// add Add some childtreenodes
foreach(DataRow dr in ds.Tables [0].Rows )
{
System.Windows.Forms.TreeNode aNode=new TreeNode(dr["Name"].ToString() );
System.Windows.Forms.TreeNode bNode=new TreeNode(dr["Name"].ToString());
treeView1.Nodes [0].Nodes[0].Nodes .Add (aNode);
treeView1.Nodes [0].Nodes[1].Nodes .Add (bNode);
}
}
}
}
}
好了,节点的值就
|