Source code for displaying ASP. NET 2.0 tree data (recursion)
Using system;
Using system. Data;
Using system. Data. sqlclient;
Using system. configuration;
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;
Public partial class _ default: system. Web. UI. Page
{
Sqlconnection conn = new sqlconnection ("workstation id =" cyz "; user id = sa; Password = ***; initial catalog = pubs; persist Security info = false ");
Dataset DS = new dataset ();
Protected void page_load (Object sender, eventargs E)
{
If (! (Ispostback ))
{
Sqldataadapter da = new sqldataadapter ("select * From t_tree order by parentid", Conn );
Da. Fill (DS, "t_tree ");
Inittree0 ();
}
}
Private void inittree0 () // function for loading the root node
{
TV. nodes. Clear (); // TV is the Treeview Control
Datarow [] rows = Ds. Tables ["t_tree"]. Select ("parentid = 0 ");
For (INT I = 0; I <rows. length; I ++)
{
Treenode t_root = new treenode ();
Datarow DR = rows [I];
T_root.text = Dr ["descricpt"]. tostring ();
TV. nodes. Add (t_root );
Inittree (t_root, Dr ["ID"]. tostring (); // After the root node is loaded, call the function for loading the child node and start recursion.
}
}
Private void inittree (treenode nd, string parent_id) // subtree node loading Function
{
Datarow [] rows = Ds. Tables ["t_tree"]. Select ("parentid =" + parent_id );
If (rows! = NULL)
{
For (INT I = 0; I <rows. length; I ++)
{
Treenode TND = new treenode ();
Datarow DR = rows [I];
TND. Text = Dr ["descricpt"]. tostring ();
Nd. childnodes. Add (TND );
Inittree (TND, Dr ["ID"]. tostring (); // recursive call
}
}
}
}
/* Post note:
I. t_tree Table Generation script
Create Table [DBO]. [t_tree] (
[ID] [int] not null,
[Parentid] [int] not null,
[Descricpt] [varchar] (50) Collate chinese_prc_ci_as null
) On [primary]
Go
Ii. t_tree table data
Parentid = 0 is the root node
Iii. Post-execution results
*/