用TreeView控件显示数据库中数据,有时用递归法是比较理想的选择,下面通过一个例子来说明一下递归法的简单应用
1 using System;
2using System.Drawing;
3using System.Collections;
4using System.ComponentModel;
5using System.Windows.Forms;
6using System.Data;
7using System.Data.OleDb;
8namespace treeview
9{
10 /// <summary>
11 /// Form1 的摘要说明。
12 /// </summary>
13 public class Form1 : System.Windows.Forms.Form
14 {
15 private System.Windows.Forms.TreeView treeView1;
16 public DataSet ds=null;
17 ///
89
90 private void Form1_Load(object sender, System.EventArgs e)
91 {
92
93 OleDbConnection con=new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Application.StartupPath+"\\n.mdb");
94 OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM ttt", con);
95 ds= new DataSet();
96 da.Fill(ds);
97 //调用递归函数,完成树形结构的生成
98 AddTree("0",(TreeNode)null);
99 }
100 // 递归添加树的节点
101 public void AddTree(string ParentID,TreeNode pNode)
102 {
103 DataView dvTree = new DataView(ds.Tables[0]);
104 //过滤ParentID,得到当前的所有子节点
105 dvTree.RowFilter= "[ParentID]='"+ParentID+"'";
106 foreach(DataRowView Row in dvTree)
107 {
108 TreeNode Node=new TreeNode() ;
109 if(pNode==null)
110 {
111 //'?添加根节点
112 Node.Text =Row["Content"].ToString();
113 this.treeView1.Nodes.Add(Node);
114 AddTree(Row["ID"].ToString(),Node); //再次递归
115 }
116 else
117 {
118 //添加当前节点的子节点
119 Node.Text = Row["Content"].ToString();
120 pNode.Nodes.Add(Node);
121 pNode.Expand();
122 AddTree(Row["ID"].ToString(),Node); //再次递归
123 }
124 }
125 }
2using System.Drawing;
3using System.Collections;
4using System.ComponentModel;
5using System.Windows.Forms;
6using System.Data;
7using System.Data.OleDb;
8namespace treeview
9{
10 /// <summary>
11 /// Form1 的摘要说明。
12 /// </summary>
13 public class Form1 : System.Windows.Forms.Form
14 {
15 private System.Windows.Forms.TreeView treeView1;
16 public DataSet ds=null;
17 ///
89
90 private void Form1_Load(object sender, System.EventArgs e)
91 {
92
93 OleDbConnection con=new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Application.StartupPath+"\\n.mdb");
94 OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM ttt", con);
95 ds= new DataSet();
96 da.Fill(ds);
97 //调用递归函数,完成树形结构的生成
98 AddTree("0",(TreeNode)null);
99 }
100 // 递归添加树的节点
101 public void AddTree(string ParentID,TreeNode pNode)
102 {
103 DataView dvTree = new DataView(ds.Tables[0]);
104 //过滤ParentID,得到当前的所有子节点
105 dvTree.RowFilter= "[ParentID]='"+ParentID+"'";
106 foreach(DataRowView Row in dvTree)
107 {
108 TreeNode Node=new TreeNode() ;
109 if(pNode==null)
110 {
111 //'?添加根节点
112 Node.Text =Row["Content"].ToString();
113 this.treeView1.Nodes.Add(Node);
114 AddTree(Row["ID"].ToString(),Node); //再次递归
115 }
116 else
117 {
118 //添加当前节点的子节点
119 Node.Text = Row["Content"].ToString();
120 pNode.Nodes.Add(Node);
121 pNode.Expand();
122 AddTree(Row["ID"].ToString(),Node); //再次递归
123 }
124 }
125 }