Use ASP.NET 2.0's TreeView to Display Hierarchical Data
Real-world Web sites need professional navigation structures. In classic ASP, developers used either custom code or third-party solutions to provide navigational elements such as TreeViews and Menus. Fortunately, ASP.NET 2.0 comes with these controls built-in. They provide not only good-looking navigational structure but also save developers from needing to write lots of code and script.
Some Basics
Before delving into the details of TreeView, get acquainted with the basics first.
Property
Description
Text
This property specifies the text that appears for that node.
Value
This property specifies a value that can be accessed programmatically when the node is clicked or expanded.
NavigateUrl
This property points to the URL of the page where the user is navigated after clicking on the node.
Target
This property indicates the destination for the URL represented by the NavigateUrl property (new windows, current windows, and so forth).
ImageUrl
This property points to the image file that is displayed for the node.
ToolTip
This property indicates the text that is displayed when the user hovers the mouse over the TreeNode text.
ImageToolTip
This property indicates the text that is displayed when the user hovers the mouse over the TreeNode image.
Adding Nodes Manually
Figure 1: Smart Tag of TreeView Control
When you select "Edit Nodes..." the IDE will open the TreeView Node Editor dialog (see Figure 2).
Figure 2: TreeView Node Editor Dialog
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>
<asp:TreeNode Text="Book Categories" Value="Book Categories">
<asp:TreeNode Text="Web Development" Value="Web Development">
<asp:TreeNode Text="ASP.NET" Value="ASP.NET"
NavigateUrl="~/example1.aspx?id=1"></asp:TreeNode>
<asp:TreeNode Text="Web Services" Value="Web Services"
NavigateUrl="~/example1.aspx?id=2"></asp:TreeNode>
<asp:TreeNode Text="JSP" Value="JSP"
NavigateUrl="~/example1.aspx?id=3"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="Windows Development"
Value="Windows Development">
<asp:TreeNode Text="Windows Forms" Value="Windows Forms"
NavigateUrl="~/example1.aspx?id=4"></asp:TreeNode>
<asp:TreeNode Text="ActiveX Controls" Value="ActiveX Controls"
NavigateUrl="~/example1.aspx?id=5"></asp:TreeNode>
<asp:TreeNode Text="Smart Client" Value="Smart Client"
NavigateUrl="~/example1.aspx?id=6"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="Component Development"
Value="Component Development">
<asp:TreeNode Text="COM" Value="COM"
NavigateUrl="~/example1.aspx?id=7"></asp:TreeNode>
<asp:TreeNode Text="DCOM" Value="DCOM"
NavigateUrl="~/example1.aspx?id=8"></asp:TreeNode>
<asp:TreeNode Text="Remoting" Value="Remoting"
NavigateUrl="~/example1.aspx?id=9"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
Now, write the following code in the SelectedNodeChanged event of the TreeView control:
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Label1.Text = "You Selected " + TreeView1.SelectedNode.Text
+ " category";
}
protected void Page_Load(object sender, EventArgs e)
{
switch (Request.QueryString["id"])
{
case "1":
Label1.Text="You selected ASP.NET category";
break;
case "2":
Label1.Text="You selected Web Services category";
break;
case "3":
Label1.Text="You selected JSP category";
break;
case "4":
Label1.Text="You selected Windows Forms category";
break;
case "5":
Label1.Text="You selected ActiveX category";
break;
case "6":
Label1.Text="You selected Smart Client category";
break;
case "7":
Label1.Text="You selected COM category";
break;
case "8":
Label1.Text="You selected DCOM category";
break;
case "9":
Label1.Text = "You selected Remoting category";
break;
}
}
Figure 3: Sample Run of Example1.aspx
Adding Nodes Programmatically
The previous example added nodes to TreeView at design time. However, in the real world, many times the data that you want to display in the TreeView resides in a database like SQL Server or Oracle. That's when you need to add tree nodes via code.
In the following example, you will build a TreeView that will display all the customers from the Customers table of the Northwind database. Selecting a customer node will add its order IDs as child nodes. This example demonstrates three things:
- Creating and adding tree nodes on the fly
- Improving performance with "on demand" population
- Filling the TreeView with data from the SQL Server database
Add a new Web form to the Web site you created previously. Drag and drop a TreeView control and add a root node to it with the Text property set to "Customers". Be sure to set its PopulateOnDemand property to true (see Figure 4). This property plays a significant role in dynamically generated TreeViews. Many times, it is not practical to populate all the nodes and child nodes of TreeView in advance. Doing so can drastically affect the performance of your Web form. The PopulateOnDemand property helps you handle such situations. When you set this property to true, clicking that node raises an event called TreeNodePopulate. Inside the TreeNodePopulate event, you write the logic to populate child nodes of the node. This way, various nodes are populated on demand.
Figure 4: Setting the PopulateOnDemand Property
Downloads
Use ASP.NET 2.0's TreeView to Display Hierarchical Data
Next, write a method called FillCustomers in the code behind. This method will be called when the user expands the root node (Customers). The method looks like this:
private void FillCustomers(TreeNode parent)
{
DataSet ds = GetDataSet("select customerid,companyname
from customers order by companyname");
foreach(DataRow row in ds.Tables[0].Rows)
{
TreeNode node=new TreeNode();
node.Text=row["companyname"].ToString();
node.Value=row["customerid"].ToString();
node.PopulateOnDemand = true;
node.SelectAction = TreeNodeSelectAction.SelectExpand;
parent.ChildNodes.Add(node);
}
}
private DataSet GetDataSet(string sql)
{
string connstr = @"data source=.\sqlexpress;
initial catalog = northwind;integrated security=true";
SqlDataAdapter da = new SqlDataAdapter(sql, connstr);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
TreeNodeSelectAction Value
Description
Expand
Raises either TreeNodeExpanded or TreeNodeCollapsed event, depending on the current expand or collapse state of the node
Select
Raises SelectedNodeChanged event when a node is selected
SelectExpand
Raises SelectedNodeChanged and TreeNodeExpanded events when a node is selected
None
Does not raise any event
private void FillOrders(TreeNode parent)
{
DataSet ds = GetDataSet("select customerid,orderid
from orders where customerid='" + parent.Value + "'");
foreach (DataRow row in ds.Tables[0].Rows)
{
TreeNode node = new TreeNode();
node.Text = row["orderid"].ToString();
node.Value = row["orderid"].ToString();
node.PopulateOnDemand = false;
node.SelectAction = TreeNodeSelectAction.SelectExpand;
parent.ChildNodes.Add(node);
}
}
Finally, add the TreeNodePopulate event handler as follows:
protected void TreeView1_TreeNodePopulate
(object sender, TreeNodeEventArgs e)
{
switch (e.Node.Depth)
{
case 0:
FillCustomers(e.Node);
break;
case 1:
FillOrders(e.Node);
break;
}
}
Figure 5 shows a sample run of the Web form.
Figure 5: Adding TreeNodes Via Code
Data Binding with XML File
Figure 6: Add New Items Dialog
Select XML File and name it Books.xml. Add the following markup to the Books.xml file:
<?xml version="1.0" encoding="utf-8" ?>
<books>
<category name="Web Development">
<subcategory name="ASP.NET" url="~/example2.aspx?id=1">
</subcategory>
<subcategory name="Web Services" url="~/example2.aspx?id=2">
</subcategory>
<subcategory name="JSP" url="~/example2.aspx?id=3">
</subcategory>
</category>
<category name="Windows Development">
<subcategory name="Windows Forms" url="~/example2.aspx?id=4">
</subcategory>
<subcategory name="ActiveX" url="~/example2.aspx?id=5">
</subcategory>
<subcategory name="Smart Client" url="~/example2.aspx?id=6">
</subcategory>
</category>
<category name="Component Development">
<subcategory name="COM" url="~/example2.aspx?id=7">
</subcategory>
<subcategory name="DCOM" url="~/example2.aspx?id=8">
</subcategory>
<subcategory name="Remoting" url="~/example2.aspx?id=9">
</subcategory>
</category>
</books>
The root node is <books> and it contains <category> nodes. The <category> nodes further contain <subcategory> nodes. The <category> tag has an attribute, called name, that represents the name of the book category. Similarly, the <subcategory> tag has an attribute, called name, that represents sub-category name. Additionally, it has an attribute, called url, that points to the Web page where the user is supposed to be navigated. Note that the name attribute corresponds to the Text property and the url attribute corresponds to the NavigateUrl property that you used previously.
Now, open the smart tag of the XmlDataSource control and choose "Configure Data Source...". This will open the dialog in Figure 7.
Figure 7: Configure Data Source Dialog
Set the DataFile property by entering the name of your XML file. Thus, books.xml will provide data to the XmlDataSource control, which in turn will be supplied to the TreeView.
Downloads
Next, open the smart tag of the TreeView control and set Data Source to XmlDataSource1 (see Figure 8).
Figure 8: Smart Tag of TreeView After Selecting Data Source
Figure 9: TreeView Databindings Editor
Under available data bindings, the dialog will automatically display the nesting of the XML file. Select "category" and click the Add button. To set the data binding, select "categoty" under the Selected data bindings list and set the TextField property to name. Note that name is an attribute of the <category> tag. By doing so, you indicate that you want to display the value of the name attribute of the <category> tag in the node. Similarly, select subcategory and set TextField and NavigateUrlField properties to name and url, respectively.
The above operations generate the following mark up for you:
<asp:TreeView ID="TreeView1" runat="server"
DataSourceID="XmlDataSource1">
<DataBindings>
<asp:TreeNodeBinding DataMember="category"
TextField="name" />
<asp:TreeNodeBinding DataMember="subcategory"
TextField="name" NavigateUrlField="url" />
</DataBindings>
</asp:TreeView>
Note how each data binding that you established in the TreeView Databindings Editor is represented by a <asp:TreeNodeBinding> markup tag.
Finally, write some code in the Page_Load event of the Web form and SelectedNodeChanged event of the TreeView to display a message when a user selects a node (as you did in the first example). The following code shows these event handlers (they are very much the same as you wrote in the first example):
protected void Page_Load(object sender, EventArgs e)
{
switch (Request.QueryString["id"])
{
case "1":
Label1.Text = "You selected ASP.NET category";
break;
case "2":
Label1.Text = "You selected Web Services category";
break;
case "3":
Label1.Text = "You selected JSP category";
break;
case "4":
Label1.Text = "You selected Windows Forms category";
break;
case "5":
Label1.Text = "You selected ActiveX category";
break;
case "6":
Label1.Text = "You selected Smart Client category";
break;
case "7":
Label1.Text = "You selected COM category";
break;
case "8":
Label1.Text = "You selected DCOM category";
break;
case "9":
Label1.Text = "You selected Remoting category";
break;
}
}
protected void TreeView1_SelectedNodeChanged
(object sender, EventArgs e)
{
Label1.Text = "You Selected " +
TreeView1.SelectedNode.Text + " category";
}
A sample run of the Web form will look exactly like Figure 3, except this time the TreeView is populated from the XML file.
A Neat, Flexible Way to Display Hierarchical Data
A professional-looking navigation system is a must for any Web site. The ASP.NET 2.0 TreeView control provides a neat and flexible way to display hierarchical data. The TreeView can be populated statically at design time or dynamically at runtime. You also can establish data binding between a TreeView and an XML file via the XmlDataSource control.
Download :
TreeView_Examples.zip - Download source code - 6 Kb
The blog is helpfull...
ReplyDeletevisit also asp.net example