Front-end:
Copy codeThe Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "Default. aspx. cs" Inherits = "TreeView. _ Default" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: TreeView ID = "TreeView1" runat = "server" ShowLines = "True">
</Asp: TreeView>
</Div>
</Form>
</Body>
</Html>
Background:
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Data;
Using System. Data. SqlClient;
Using System. Configuration;
Namespace TreeView
{
Public partial class _ Default: System. Web. UI. Page
{
Public static string st = ConfigurationManager. ConnectionStrings ["SQL"]. ToString ();
Private DataTable dts = new DataTable ();
Protected void Page_Load (object sender, EventArgs e)
{
If (! IsPostBack)
{
Dts = CreateTable ();
CreateNode ();
}
}
Public void CreateNode ()
{
DataRow [] dr = dts. Select ("ParentID = 0 ");
If (dr. Length> 0)
{
Foreach (DataRow drr in dr)
{
TreeNode tn = new TreeNode ();
Tn. Value = drr ["MenuID"]. ToString ();
Tn. Text = drr ["MenuName"]. ToString ();
Tn. Expanded = false;
Tn. SelectAction = TreeNodeSelectAction. Expand;
TreeView1.Nodes. Add (tn );
CreateChild (tn, dts );
}
}
Else
{
TreeNode t = new TreeNode ();
T. Value = "null ";
T. Text = "null ";
T. Expanded = false;
T. SelectAction = TreeNodeSelectAction. Expand;
TreeView1.Nodes. Add (t );
}
}
Public void CreateChild (TreeNode tnn, DataTable dtt)
{
DataRow [] dr = dtt. Select ("ParentID =" + tnn. Value );
If (dr. Length> 0)
{
Foreach (DataRow drw in dr)
{
TreeNode ts = new TreeNode ();
Ts. Value = drw ["MenuID"]. ToString ();
Ts. Text = drw ["MenuName"]. ToString ();
Ts. SelectAction = TreeNodeSelectAction. Expand;
Ts. Expanded = false;
Tnn. ChildNodes. Add (ts );
CreateChild (ts, dtt );
}
}
}
Public DataTable CreateTable ()
{
DataTable d = new DataTable ();
Using (SqlConnection SQL = new SqlConnection (st ))
{
SqlCommand sq = new SqlCommand ("select * from TreeViewName", SQL );
SqlDataAdapter sda = new SqlDataAdapter ();
Sda. SelectCommand = sq;
Sda. Fill (d );
}
Return d;
}
}
}