ASP.Net Code

ASP.Net 2.0 – Traverse the TreeView Control to Find a Node

This function will enable you to traverse a populated TreeView control, and find and select a node based on it's value and the value you specify. This will work no matter how deep the branches of the tree go!

For a step-by-step explanation of this code, you can read my tutorial.


<%@ Page Language="C#" CompileWith="tree.aspx.cs" ClassName="tree_aspx" Debug="true" %>
<!DOCTYPE html PUBLIC "-//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>Select item from treeview</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TreeView ID="TreeView1" Runat="server" OnSelectedNodeChanged="changeInt">
        <SelectedNodeStyle BackColor="#cccc99"></SelectedNodeStyle>
        </asp:TreeView>
    </form>
</body>
</html>

And here's the code-behind

using System;
using System.Data ;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls ;

public partial class tree_aspx
{

protected Int64 testInt;
bool intNodeFound = false;

void page_load(object s, EventArgs e)
{
if (!IsPostBack)
{
TreeNode t = new TreeNode("1");
TreeNode t2 = new TreeNode("2");
TreeNode t3 = new TreeNode("3");
TreeNode t4 = new TreeNode("4");
TreeNode t5 = new TreeNode("5");
TreeView1.Nodes.Add(t);
TreeView1.Nodes.Add(t2);
TreeView1.Nodes[0].ChildNodes.Add(t3);
TreeView1.Nodes[1].ChildNodes.Add(t4);
TreeView1.Nodes[1].ChildNodes.Add(t5);
TreeView1.Nodes[0].ToggleExpandState();
TreeView1.Nodes[1].ToggleExpandState();
TreeView1.CollapseAll();

try
{
testInt = Convert.ToInt64 (Request.QueryString["id"]);
}
catch (ArgumentNullException x)
{

}
catch (FormatException f)
{
Response.Write (Request.QueryString["id"] + " is invalid!");
}
ViewState["testInt"] = testInt;
FindNodeByValue(TreeView1.Nodes, testInt.ToString());
}
else
{
testInt = Convert.ToInt64(ViewState["testInt"]);
}
}

void FindNodeByValue(TreeNodeCollection n, string val)
{
if (intNodeFound) return;

for (int i = 0; i < n.Count; i++) { if (n[i].Value == val) { n[i].Select(); intNodeFound = true; return; } n[i].Expand(); FindNodeByValue(n[i].ChildNodes, val); if (intNodeFound) return; n[i].Collapse(); } } } [/code]

Share

4 Comments

  1. Thank you. Your code works flawlessly.

  2. where is the changeInt function????? my page shows error

  3. where is the changeInt function?????

  4. Thanks, After couple of hours search, I found this solution. Excellent solution.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image