选中TreeView的某节点,并加背景颜色

一:按钮事件,遍历所有节点

private void button2_Click(object sender, EventArgs e)
        {            

            foreach (TreeNode n in TreeView1.Nodes)
            {
                ErgodicTreeView(n);
            }
        }
void ErgodicTreeView(TreeNode tn)
        {
            if (tn == null) return;
            //查找到某节点时
            if (tn.Text.Equals("英山县"))
            {
                //遍历递归获取父节点,将父节点全部展开
                prenode(tn);
                //选中某节点,并加背景颜色
                TreeView1.SelectedNode = tn;
                TreeView1.SelectedNode.BackColor = System.Drawing.Color.Red;
            }
            foreach (TreeNode n in tn.Nodes)
            {
                ErgodicTreeView(n);
            }
        }
        void prenode(TreeNode m)
        {
           

            if (m.Parent.Text != null)
            {
                m.Parent.Expand();
                //当为项级节点时
                if (m.Parent.Level == 0)
                {
                    m.Parent.Expand();
                }
                 //不是项级节点时
                else
                {
                    prenode(m.Parent);
                }

            }
           
        }

 

如图:

 

posted @ 2013-07-14 18:34  小锋神  阅读(16038)  评论(0编辑  收藏  举报