ASP. NET recursively add Tree nodes

Source: Internet
Author: User

Table Design:

Id title parentid

1 Asp.net 0
2 C #0
3 C # _ 0 2
4 C # _ 1 3
5 C # _ 2 4

 

Add a Treeview control to the page.

 

Add nodes by writing:

Private void addnode (int id, treenode parentnode)
{
String SQL = "select * From menu"; // SQL statement
Datatable table = dB. getdb (SQL); // get data

Dataview view = new dataview (table); // Add Table data to the custom View

View. rowfilter = "parentid =" + ID; // set View query Conditions

Foreach (datarowview row in view) // traverses the data in the view
{
Treenode node = new treenode ();

Node. Text = row [1]. tostring ();
Int newid = convert. toint32 (row [0]);

If (parentnode! = NULL)
{
Node. Expanded = false;
Parentnode. childnodes. Add (node );
Addnode (newid, node); // recursive node search
}
Else
{
Treeview1.nodes. Add (node );
Addnode (newid, node );
}

}
}

 

Getdb () method in dB class:

Public static sqlconnection sqlconn ()
{
String sqlconnstr = "database = menutree; Data Source =.; uid = sa; Pwd = 123 ";

Sqlconnection conn = new sqlconnection (sqlconnstr );
Return conn;
}

Public static datatable getdb (string SQL)
{
Sqlconnection connection = sqlconn ();
Sqlcommand comm = new sqlcommand (SQL, connection );

Sqldataadapter ad = new sqldataadapter (Comm );
Datatable table = new datatable ();
Ad. Fill (table );
Return table;
}

 

 

CallCode:

 

Protected void page_load (Object sender, eventargs E)
{

If (! Ispostback)
{
Treeview1.nodes. Clear ();
Addnode (0, (treenode) null );
}
}

Done!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.