始现在好多方法都是先生成XML,然后在生成TreeView。其实,本身创建一个动态的TreeView并不是件很复杂的事。
以下就具体说明,如何产生一个动态的树:
首先,为这个树先要获取数据,如下:
private DataTable dtTree = null;
private DataView dv = null;
private void CreateTable()
{
dtTree = new DataTable( "TreeDBInfo" );
dtTree.Columns.Add( new DataColumn( "TypeID", typeof(int) ) );
dtTree.Columns.Add( new DataColumn( "TypeName", typeof(string) ) );
dtTree.Columns.Add( new DataColumn( "TypeParentID", typeof(int) ) );
dtTree.Rows.Add( new object[]{1, "Parent1", 0} );//'0' is that the type has no parent
dtTree.Rows.Add( new object[]{2, "Parent2", 0} );
dtTree.Rows.Add( new object[]{3, "Parent3", 0} );
dtTree.Rows.Add( new object[]{ 4, "Child1", 1} );
dtTree.Rows.Add( new object[]{ 5, "Child2", 1} );
dtTree.Rows.Add( new object[]{ 6, "Child3", 2} );
dtTree.Rows.Add( new object[]{ 7, "GrandChild1", 4} );
dtTree.Rows.Add( new object[]{ 8, "GrandChild2", 4} );
dtTree.Rows.Add( new object[]{ 9, "GrandChild3", 5} );
}
这是一个简单的属性结构,如果要从数据库读出的话,只要为dtTable指定为已经在DataSet填充好的Table即可,这里就不细说了。
接下来,就是生成树的函数,如下:
private void CreateTree()
{
dv = dtTree.DefaultView;
dv.Sort = "TypeParentID ASC";
DataRowView[] arrDRV = dv.FindRows( 0 );//Get root data info
if( arrDRV.Length == 0 ) return;
TreeNode tnNew = null;
foreach( DataRowView drv in arrDRV )
{
tnNew = trvDBBinding.Nodes.Add( drv.Row["TypeName"].ToString() );
tnNew.Tag = drv.Row["TypeID"].ToString();//Save "TypeID" in node's tag
CreateTreeNode( ref tnNew );
}
}
private void CreateTreeNode( ref TreeNode tnParent )
{
DataRowView[] arrDRV = dv.FindRows( tnParent.Tag );//Get children data info
if( arrDRV.Length == 0 ) return;
TreeNode tnNew = null;
foreach( DataRowView drv in arrDRV )
{
tnNew = tnParent.Nodes.Add( drv.Row["TypeName"].ToString() );
tnNew.Tag = drv.Row["TypeID"].ToString();//Save "TypeID" in node's tag
CreateTreeNode( ref tnNew );
}
}
简单调用如下:
CreateTable();
CreateTree();
本文作者:网友 来源:博客园愚翁专栏