在网上看了天轰穿老师的TreeView这一节课,他讲的很简单,代码如下:
数据库结构:第一个表是big,第二个表是class
代码如下:
private
void
Form2_Load(
object
sender, EventArgs e)
{
DataView dv
=
drv(
"
select bid,title from big
"
);
TreeNode n
=
new
TreeNode();
n.Text
=
"
中国地区
"
;
this
.treeView1.Nodes.Add(n);
foreach
(DataRowView datav
in
dv)
{
TreeNode tn
=
new
TreeNode();
tn.Text
=
datav[
"
title
"
].ToString();
tn.Tag
=
datav[
"
bid
"
];
n.Nodes.Add(tn);
AddChildNodes(tn);
}
//
ExpandNode(this.treeView1.Nodes);
}
private
DataView drv(
string
sql)
{
SqlConnection con
=
new
SqlConnection(
"
server=.;database=test;uid=sa;pwd=;
"
);
SqlDataAdapter sda
=
new
SqlDataAdapter(sql, con);
DataTable dt
=
new
DataTable();
sda.Fill(dt);
return
dt.DefaultView;
}
private
void
AddChildNodes(TreeNode t)
{
int
bid
=
Convert.ToInt32(t.Tag.ToString());
DataView d
=
drv(
"
select * from class where bid=
"
+
bid);
foreach
(DataRowView datav
in
d)
{
TreeNode node
=
new
TreeNode();
node.Text
=
datav[
"
title
"
].ToString();
node.Tag
=
datav[
"
cid
"
];
t.Nodes.Add(node);
}
}
/*
private void ExpandNode(TreeNodeCollection tnc)
{
foreach (TreeNode node in tnc)
{
node.Expand();
ExpandNode(node.Nodes);
}
}
*/
可是我在做项目时需要根据一个表中的数据来显示树形目录,数据库结构如下:
构件树形目录的方法如下:
#region
构建TreeView
public
bool
BuildTree(TreeView tv, DataSet ds)
{
tv.Nodes.Clear();
foreach
(DataRow dbRow
in
ds.Tables[
0
].Rows)
{
if
(dbRow[
"
FatherNumber
"
].ToString()
==
string
.Empty)
{
dbRow[
"
FatherNumber
"
]
=
DBNull.Value;
}
}
ds.Relations.Add(
"
NodeRelation
"
, ds.Tables[
0
].Columns[
"
TypeNumber
"
], ds.Tables[
0
].Columns[
"
FatherNumber
"
],
false
);
foreach
(DataRow dbRow
in
ds.Tables[
0
].Rows)
{
if
(dbRow.IsNull(
"
FatherNumber
"
))
{
TreeNode newNode
=
CreateNode(dbRow[
"
TypeName
"
].ToString(), dbRow[
"
TypeNumber
"
].ToString());
tv.Nodes.Add(newNode);
PopulateSubTree(dbRow, newNode);
}
}
//
展开所有节点
tv.ExpandAll();
return
true
;
}
private
void
PopulateSubTree(DataRow dbRow, TreeNode node)
{
foreach
(DataRow childRow
in
dbRow.GetChildRows(
"
NodeRelation
"
))
{
TreeNode childNode
=
CreateNode(childRow[
"
TypeName
"
].ToString(), childRow[
"
TypeNumber
"
].ToString());
node.Nodes.Add(childNode);
PopulateSubTree(childRow, childNode);
}
}
private
TreeNode CreateNode(
string
text,
string
tag)
{
TreeNode node
=
new
TreeNode();
node.Text
=
text;
node.Tag
=
tag;
return
node;
}
这样调用:
SqlConnection con
=
new
SqlConnection(
"
server=192.168.1.192;database=AUDE_KCGL;uid=sa;pwd=;
"
);
SqlDataAdapter sda
=
new
SqlDataAdapter(
"
select TypeNumber,FatherNumber,TypeName from KC_ObjectType
"
, con);
DataSet dsTree
=
new
DataSet();
sda.Fill(dsTree);
//
调用方法构件树形目录
BuildTree(
this
.treeView1, dsTree);
程序运行效果: