Suppose you create a table in the database, such as Tb_treeview, as follows
CREATE TABLE Tb_treeview (
ID int NOT NULL,
DisplayName varchar (20),
ParentID int,
URL varchar (100)
);
Insert several data into a table such as:
INSERT into Tb_treeview (1, ' China ', 0, ');
Insert into Tb_treeview (2, ' Anhui Province ', 1, ');
Insert into Tb_treeview (3, ' Hefei ', 2, ');
Insert into Tb_treeview (4, ' Jiangsu Province ', 1, ');
Insert into Tb_treeview (5, ' Nanjing ', 4, ');
INSERT into Tb_treeview (6, ' Hubei province ', 1, ');
As presentation data.
(1), open VS2005, create a new Web site project, add the following code in the Default.aspx.cs file:
...
Using System.Data.SqlClient;
....
DataTable dt = new DataTable ();
public void Page_Load (Object Sender,eventargs e)
{
if (! IsPostBack)
{
Try
{
String constring = "Data source=.; uid=sa;pwd=;D Atabase=master ";
SqlConnection con = new SqlConnection (constring);
Con. Open ();
String strSQL = "SELECT * from Tb_treeview";
SqlDataAdapter da = new SqlDataAdapter (Strsql,con);
Da. Fill (DT);
}
catch (Exception e)
{
}
Finally
{
Con. Close ();
}
Addtreenode (0, (TreeNode) null);
}
}
protected void Addtreenode (int parentid,treenode pnode)
{
TreeNode tn1 = new TreeNode ();
DataView dv= new DataView (DT);
Filter ParentID to get all child nodes of the current node
Dv. RowFilter = "parentid=" +parentid;
foreach (DataRowView DRV in DV)
{
if (pnode==null)
{
Tn1. Text = drv["DisplayName"]. ToString (); The name to display on the node
Tn1. NavigateUrl = drv["url"]. ToString (); Click on the node name to jump to the specified URL page
TREEVIEW1.NODES.ADD (TN1); Add the root node to the TreeView
Tn1. Expanded = true;
Recursive call
Addtreenode (Int32.Parse (drv["id"). ToString ()), TN1);
}
Else
{
TreeNode tn2 = new TreeNode ();
Tn2. Text = drv["DisplayName"]. ToString ();
Tn2. NavigateUrl = drv["url"]. ToString ();
PNODE.CHILDNODES.ADD (TN2);
Tn1. Expanded = true;
Recursive call
Addtreenode (Int32.Parse (drv["id"). ToString ()), TN2);
}
}
}
(2), run in the browser, open the effect as follows
+ China
|+ Anhui Province
| |_ Hefei City
|+ Jiangsu Province
| |_, Nanjing
|+ Hubei Province
It should be explained that in actual development, the data access to the database should be placed in the DAL layer, here is just a simple demo.
If you want to change the node you have selected and the rendering color of the font when you move to that node, you can set this:
<asp:treeview id= "TreeView1" runat= "Server" showlines= "True" cssclass= "Menu" >
<rootnodestyle forecolor= "Red"/>
<selectednodestyle forecolor= "Gray"/>
</asp:TreeView>