Example of binding Treeview data and dynamically adding nodes in asp.net

Source: Internet
Author: User
Tags xmlns access database connectionstrings

TreeView data binding

In ASP. NET, how does one bind data between databases and TreeView controls? Take some time to write a demo program, including an Access database. You can copy the two codes for testing and download the database file.
The Left. aspx code is as follows:

The code is as follows: Copy code

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Left. aspx. cs" Inherits = "Left" %>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head id = "Head1" runat = "server">
<Title> demonstrate the TreeView data binding method </title>
<Script language = "javascript">
Function chkAll ()
{
Var chkall = document. all ["chkall"];
Var chkother = document. getElementsByTagName ("input ");
For (var I = 0; I <chkother. length; I ++)
    {
If (chkother [I]. type = 'checkbox ')
        {
If (chkother [I]. id. indexOf ('treeview1')>-1)
            {
If (chkall. checked = true)
                {
Chkother [I]. checked = true;
                }
Else
                {
Chkother [I]. checked = false;
                }
            }
        }
    }
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Table width = 100% height = 100%>
<Tr height = 10>
<Td> <input id = "chkall" type = "checkbox" onclick = "chkAll ();"/> Select All/cancel </td>
<Td> <asp: Button ID = "Button1" runat = "server" Text = "Button"/> </td>
</Tr>
<Tr valign = top>
<Td> <asp: TreeView ID = "TreeView1" runat = "server"> </asp: TreeView> </td>
<Td> <iframe id = fMain style = "BORDER-TOP-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BORDER-BOTTOM-STYLE: none "src =" "frameBorder =" 0 "width =" 100% "scrolling =" yes "height =" 100% "> </iframe> </td>
</Tr>
<Tr height = 10>
<Td> </td>
</Tr>
</Table>
</Form>
</Body>
</Html>

Left. aspx. cs code, which is in the same directory as Left. aspx:

The code is as follows: Copy code

Using System;
Using System. Data;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. HtmlControls;
Using System. Data. SqlClient;
Public partial class Left: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
    {
If (! Page. IsPostBack)
        {
BindTree ();
// InitTree ();
        }
    }
# Region master/slave table binding
Private void BindTree ()
    {
DataSet dst = GetTreeViewData ();
TreeView1.ShowCheckBoxes = TreeNodeTypes. All;
Foreach (DataRow masterRow in dst. Tables ["province"]. Rows)
        {
TreeNode masterNode = new TreeNode (string) masterRow ["province"]);
TreeView1.Nodes. Add (masterNode );
Foreach (DataRow childRow in masterRow. GetChildRows ("Children "))
            {
TreeNode childNode = new TreeNode (string) childRow ["city"]);
MasterNode. Expanded = false;
MasterNode. ChildNodes. Add (childNode );
            }
        }
    }
Private DataSet GetTreeViewData ()
    {
String constring = System. Configuration. ConfigurationSettings. Deleettings ["ConnectionStr"];
SqlConnection con = new SqlConnection (constring );
SqlDataAdapter daprovince = new SqlDataAdapter ("SELECT * FROM province", con );
SqlDataAdapter dacity = new SqlDataAdapter ("SELECT * FROM city", con );
DataSet ds = new DataSet ();
Daprovince. Fill (ds, "province ");
Dacity. Fill (ds, "city ");
Ds. relations. add ("Children", ds. tables ["province"]. columns ["provinceid"], ds. tables ["city"]. columns ["father"]);
Return ds;
    }
# Endregion
# Region recursively binds data in the same table
Private void InitTree ()
    {
DataTable dt = GetTreeViewTable ();
DataView dv = new DataView (dt );
Dv. RowFilter = "ParentID = 0 ";
TreeView1.ShowCheckBoxes = TreeNodeTypes. All;
Foreach (DataRowView drv in dv)
        {
TreeNode node = new TreeNode ();
Node. Text = drv ["text"]. ToString ();
Node. Value = drv ["ID"]. ToString ();
Node. Expanded = false;
TreeView1.Nodes. Add (node );
AddReplies (dt, node );
        }
    }
Private DataTable GetTreeViewTable ()
    {
String constring = System. Configuration. ConfigurationSettings. Deleettings ["ConnectionStr"];
SqlConnection con = new SqlConnection (constring );
SqlDataAdapter da = new SqlDataAdapter ("SELECT * FROM treeview", con );
DataTable dt = new DataTable ();
Da. Fill (dt );
Return dt;
    }
Private void AddReplies (DataTable dt, TreeNode node)
    {
DataView dv = new DataView (dt );
Dv. RowFilter = "ParentID = '" + node. Value + "'";
Foreach (DataRowView row in dv)
        {
TreeNode replyNode = new TreeNode ();
ReplyNode. Text = row ["text"]. ToString ();
ReplyNode. Value = row ["ID"]. ToString ();
ReplyNode. Expanded = false;
Node. ChildNodes. Add (replyNode );
AddReplies (dt, replyNode );
        }
    }
# Endregion
}


Add node instances dynamically in Treeview


When using TreeView in asp.net, it is easy to add node data statically. However, in general, TreeView dynamically displays menu items, most of the content is loaded from XML, Access, and SqlServer databases. It is not difficult to read the content from the database to dynamically add nodes. For example, we use the SQL2000 PUBS database as an example, we extract the "author" as the root node in the tree list, and then extract the work of the corresponding author as the subnode to dynamically expand and load the data TreeView. We can do this:

The code is as follows: Copy code
<% @ Page Language = "C #" %>
<% @ Import Namespace = "System. Data" %>
<% @ Import Namespace = "System. Data. SqlClient" %>
<% @ Import Namespace = "System. Configuration" %>
<! DOCTYPE htmlPUBLIC "-// W3C // dtd xhtml 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> Dynamic Population of the TreeView Control </title>
<Script runat = server>
Void Node_Populate (object sender,
System. Web. UI. WebControls. TreeNodeEventArgs e)
{
If (e. Node. ChildNodes. Count = 0)
{
Switch (e. Node. Depth)
{
Case 0:
FillAuthors (e. Node );
Break;
Case 1:
FillTitlesForAuthors (e. Node );
Break;
}
}
}
Void FillAuthors (TreeNode node)
{
String connString = System. Configuration. ConfigurationSettings.
ConnectionStrings ["NorthwindConnnection"]. ConnectionString;
SqlConnection connection = new SqlConnection (connString );
SqlCommand command = new SqlCommand ("Select * From
Authors ", connection );
SqlDataAdapter adapter = new SqlDataAdapter (command );
DataSet authors = new DataSet ();
Adapter. Fill (authors );
If (authors. Tables. Count> 0)
{
Foreach (DataRow row in authors. Tables [0]. Rows)
{
TreeNode newNode = new
TreeNode (row ["au_fname"]. ToString () + "" +
Row ["au_lname"]. ToString (),
Row ["au_id"]. ToString ());
NewNode. PopulateOnDemand = true;
NewNode. SelectAction = TreeNodeSelectAction. Expand;
Node. ChildNodes. Add (newNode );
}
}
}
Void FillTitlesForAuthors (TreeNode node)
{
String authorID = node. Value;
String connString = System. Configuration. ConfigurationSettings.
ConnectionStrings ["NorthwindConnnection"]. ConnectionString;
SqlConnection connection = new SqlConnection (connString );
SqlCommand command = new SqlCommand ("Select T. title,
T. title_id From titles T "+
"Inner Join titleauthor TA on
T. title_id = TA. title_id "+
"Where TA. au_id = '" + authorID + "'", connection );
SqlDataAdapter adapter = new SqlDataAdapter (command );
DataSet titlesForAuthors = new DataSet ();
Adapter. Fill (titlesForAuthors );
If (titlesForAuthors. Tables. Count> 0)
{
Foreach (DataRow row in titlesForAuthors. Tables [0]. Rows)
{
TreeNode newNode = new TreeNode (
Row ["title"]. ToString (), row ["title_id"]. ToString ());
NewNode. PopulateOnDemand = false;
NewNode. SelectAction = TreeNodeSelectAction. None;
Node. ChildNodes. Add (newNode );
}
}
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: TreeViewRunat = "Server" ExpandImageUrl = "Images/closed.gif"
CollapseImageUrl = "Images/open.gif"
OnTreeNodePopulate = "Node_Populate" ID = "tvwauthors">
<Nodes>
<Asp: TreeNodeText = "Authors" PopulateOnDemand = true
Value = "0"/>
</Nodes>
</Asp: TreeView>
</Div>
</Form>
</Body>
</Html>

Note that the ontreenodepopulate event occurs when the tree node is expanded. node_populate is defined here to check the depth of the current node. If it is 0, it is the root node, therefore, the FillAuthors process is called to retrieve all authors. If the depth is 1, it is a subnode and the FillTitlesForAuthors process is called to read the work information. The following code dynamically creates a tree node:

The code is as follows: Copy code
TreeNode newNode = new TreeNode (row ["au_fname"]. ToString () + "" +
Row ["au_lname"]. ToString (),
Row ["au_id"]. ToString ());
NewNode. PopulateOnDemand = true;
NewNode. SelectAction = TreeNodeSelectAction. Expand;
Node. ChildNodes. Add (newNode );

According to the attributes of popluateondemand, this node can be dynamically expanded.

Related Article

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.