Click here to Skip to main content
16,020,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,
i have a treecontrol in windows for application i need get the structure like below

greandparent
parent1
parent2
child1
how can do it can any onw pls help me
Posted

1 solution

Just use the Parent-Property of the TreeNode (if it's null there is no parent). So if you look for the "grandparent" just use Parent.Parent -> Look at this example: (Just copy to a new WindowsForms project and replcace Program.cs with the following:)

using System;
using System.Windows.Forms;

namespace TreeViewTest
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            // Create a Form
            Form form = new Form();

            // Create a Label for Relation Info
            Label labelInfo = new Label();
            labelInfo.Height = 50;
            labelInfo.Dock = DockStyle.Top;

            // Create a Treeview
            TreeView treeview = new TreeView();
            treeview.Dock = DockStyle.Fill;
            // Update Relation Info after Selected Node changes
            treeview.AfterSelect += delegate(object sender, TreeViewEventArgs e)
            {
                labelInfo.Text = String.Format("I'm {0}, my parent is {1}, my grandparent is {2}",
                    e.Node.Text,
                    e.Node.Parent != null ? e.Node.Parent.Text : "dead",
                    e.Node.Parent != null && e.Node.Parent.Parent != null ? e.Node.Parent.Parent.Text : "dead");
            };
            // Create and ...
            TreeNode nodeGrandParent = new TreeNode("Grandparent");
            TreeNode nodeParentMom = new TreeNode("ParentMom");
            TreeNode nodeParentDad = new TreeNode("ParentDad");
            TreeNode nodeChild = new TreeNode("Child");
            // ...add the example node structure to the treeview
            nodeGrandParent.Nodes.Add(nodeParentMom);
            nodeGrandParent.Nodes.Add(nodeParentDad);
            nodeParentMom.Nodes.Add(nodeChild);
            treeview.Nodes.Add(nodeGrandParent);

            // Add the Controls to the form
            form.Controls.Add(treeview);
            form.Controls.Add(labelInfo);
            // ... and run it
            Application.Run(form);
        }
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900