From: http://www.cnblogs.com/hooyes/archive/2008/05/16/1199553.html
Asp.net 2.0 Treeview is dynamically filled and an infinite level tree is implemented,
Keyword field of the database table:
Table: Table1
Type_id type_name per_type_id
0 Root directory- 1
1 Subdirectory 0
2 Subdirectory 2 0
3 Sub-Directories 2
.
9 Root directory 2- 1
C # Code Using System;
Using System. Data;
Using System. configuration;
Using System. collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. webcontrols;
Using System. Web. UI. webcontrols. webparts;
Using System. Web. UI. htmlcontrols;
Using System. Data. sqlclient;
Public Partial Class Tree: system. Web. UI. Page
{
Protected Void Page_load ( Object Sender, eventargs E)
{
Treeview1.nodes. Clear ();
Datatable dt = Tree_table ();
Dataview dv = New Dataview (DT );
DV. rowfilter = " Type_id = 0 " ;
Foreach (Datarowview DRV In DV)
{
Treenode Node = New Treenode ();
Node. Text = DRV [ " Type_name " ]. Tostring ();
Node. Value = DRV [ " Type_id " ]. Tostring ();
Node. navigateurl = " ? S = " + DRV [ " Type_id " ]. Tostring ();
Treeview1.nodes. Add (node );
Addchildnode (DT, node );
}
}
Private Datatable tree_table ()
{
// Hooyesdatalink is the data connection string key name in the configuration.
Sqlconnection con = New Sqlconnection (configurationmanager. receivettings [ " Hooyesdatalink " ]);
Sqldataadapter SDA = New Sqldataadapter ( " Select * From Table1 " , Con );
Datatable dt = New Datatable ();
SDA. Fill (DT );
Return DT;
}
Recursion to implement an infinite level tree # Region Recursion to implement an infinite level tree
Private Void Addchildnode (datatable DT, treenode node)
{
Dataview dv = New Dataview (DT ); // Create a table view for dt
DV. rowfilter = " Per_type_id =' " + Node. Value + " ' " ; // Filter
Foreach (Datarowview drv1 In DV)
{
Treenode childnode = New Treenode ();
Childnode. Text = Drv1 [ " Type_name " ]. Tostring ();
Childnode. Value = Drv1 [ " Type_id " ]. Tostring ();
Childnode. navigateurl = " ? S = " + Drv1 [ " Type_id " ]. Tostring ();
Childnode. Expanded = True ; // Show property is false
Node. childnodes. Add (childnode );
Addchildnode (DT, childnode );
}
}
# Endregion
}
Effect: