How to bind ASP. Net data to the tree [TreeView]
This example provides two solutions in the same principle.
The returned list is also bound.
The Code is as follows. -------- To us who are still cainiao
Create a table
Create table Tree
(
ID int primary key not null,
Title varchar (20) not null,
Url varchar (100 ),
ParentID int not null
)
Go
Insert into Tree (ID, Title, ParentID)
Values (1, 'System settings',-1)
Insert into Tree (ID, Title, ParentID)
Values (2, 'Park management',-1)
Insert into Tree (ID, Title, ParentID)
Values (3, 'rating management',-1)
Insert into Tree (ID, Title, ParentID)
Values (4, 'metric management',-1)
Insert into Tree (ID, Title, Url, ParentID)
Values (6, 'user maintain', 'user/UserInfo. aspx ', 1)
Insert into Tree (ID, Title, Url, ParentID)
Values (7, 'Role maintain', 'user/PartInfo. aspx ', 1)
Insert into Tree (ID, Title, Url, ParentID)
Values (8, 'Password', 'user/ChangPwd. aspx ', 1)
Insert into Tree (ID, Title, Url, ParentID)
Values (9, 'Park maintain', 'gardenarea/GardenAreaEdit. aspx ', 2)
Insert into Tree (ID, Title, Url, ParentID)
Values (10, 'Contact maintain', 'gardenarea/GaContact1.aspx ', 2)
Insert into Tree (ID, Title, Url, ParentID)
Values (11, 'Evaluation maintenance ', 'certifbody body/certifbody body. aspx', 3)
Insert into Tree (ID, Title, Url, ParentID)
Values (12, 'Contact maintain', 'certificationbody/CbContact. aspx ', 3)
Insert into Tree (ID, Title, Url, ParentID)
Values (13, 'indicator maintenance ', 'Indicators/Indicators. aspx', 4)
Insert into Tree (ID, Title, Url, ParentID)
Values (14, 'rating rating defination', 'Indicators/DegreeDefine. aspx ', 4)
Insert into Tree (ID, Title, Url, ParentID)
Go
Page code
Public void BindData ()
{
String connString = "Server = PRODUCT; Database = Database name; uid = sa; pwd = sa ";
SqlConnection sqlcon = new SqlConnection (connString );
SqlDataAdapter da = new SqlDataAdapter ("select * from Tree", sqlcon );
DataTable dt = new DataTable ();
Da. Fill (dt );
// BindTreeView (dt, TreeView1.Nodes,-1 );
BindTree (dt, null,-1 );
}
Public void BindTree (DataTable dt, TreeNode ptn, int pid)
{
DataRow [] drs = dt. Select ("ParentID =" + pid );
Foreach (DataRow B in drs)
{
TreeNode tn = new TreeNode ();
Tn. Value = B ["ID"]. ToString ();
Tn. Text = B ["Title"]. ToString ();
Tn. NavigateUrl = B ["Url"]. ToString ();
If (ptn = null)
{
TreeView1.Nodes. Add (tn );
}
Else
{
Ptn. ChildNodes. Add (tn );
}
BindTree (dt, tn, Convert. ToInt32 (tn. Value ));
}
}
Private void BindTreeView (DataTable dt, TreeNodeCollection tnc, int pid)
{
DataRow [] drs = dt. Select ("ParentID =" + pid );
Foreach (DataRow B in drs)
{
TreeNode tn = new TreeNode ();
Tn. Value = B ["ID"]. ToString ();
Tn. Text = B ["Title"]. ToString ();
Tn. NavigateUrl = B ["Url"]. ToString ();
Tnc. Add (tn );
BindTreeView (dt, tn. ChildNodes, Convert. ToInt32 (tn. Value ));
}
}