是否可以通过编程方式选择其中一个子节点

时间:2010-10-02 12:25:49

标签: c# winforms treeview

我想以编程方式选择我的树视图中的一个子节点。我的树视图在运行时如下

      Root
       |->A.txt(I would like to select this node after doing some iteration in my application)
         |->Child(Even if i select this node and do some operations i would like to select the above one only like that if n number of child nodes exists i would like to select the node that was with .txt extension)

我已经编写了以下代码,它工作正常,但有一次我无法做到这一点可以帮助

这是我的代码

     if (tvwACH.Nodes.Count != 0)
            {
               // tvwACH.ExpandAll();
                TreeNode tn;
                tn = tvwACH.Nodes[0];
                tvwACH.ExpandAll();
                if  (tn.Nodes.Count != 0)
                {
                    tn = tn.Nodes[0];
                }
                if (tn.Tag.ToString() == "3")
                {
                    if (tvwACH.SelectedNode.Parent != null)
                    {
                        tn.Parent.Expand();
                        tvwACH.SelectedNode = tn;
                    }
                }
            }

我的最终树视图如下

            Root
              |->Some.txt
                |->Child
                  |->Sub Child
                     |->Child (for subchild) // After this i will not have any nodes so my code works up to Sub Child but if i added some thing after clicking Child after subchild  i am unable to select the node i meeded as it has no nodes can any one help me out please

1 个答案:

答案 0 :(得分:0)

Atlast我得到了答案

        TreeNode TvNode = tvwACH.SelectedNode.Parent;

            while (TvNode != null)
            {
                if (TvNode.Text.EndsWith(".txt", true, System.Globalization.CultureInfo.InvariantCulture))
                {
                    tvwACH.SelectedNode = TvNode;
                    TvNode = null;
                }
                else
                    TvNode = TvNode.Parent;
            }