Asp. NET Recursive Add tree node

Source: Internet
Author: User

Table Design:

ID Title ParentID

1 ASP. 0

2 C # 0

3 C#_0 2

4 C#_1 3

5 C#_2 4

Add a TreeView control to the page

Write Add Node Method:

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 Custom view

View. RowFilter = "Parentid=" +id;//set view query criteria

foreach (DataRowView row in view)//Traverse data in 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 lookup node

}

Else

{

TREEVIEW1.NODES.ADD (node);

AddNode (newid, node);

}

}

}

The Getdb () method in the 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; }

Calling code:

protected void Page_Load (object sender, EventArgs e)

{if (! IsPostBack)

{TreeView1.Nodes.Clear ();

AddNode (0, (TreeNode) null);
}     }

Complete!

Asp. NET Recursive Add tree node

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.