如何在c-sharp中获取子节点的祖父母

如何在c-sharp中获取子节点的祖父母

问题描述:


我在Windows中有一个适用于应用程序的Windows控件,我需要获取如下结构

greandparent
parent1
parent2
child1
怎么做才能对我有帮助?


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

只需使用TreeNode的Parent-Property(如果它为null,则没有父级).因此,如果您寻找祖父母",只需使用Parent.Parent->看下面的示例:(只需复制到新的WindowsForms项目并使用以下命令替换Program.cs :)

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);
        }
    }
}