C#中遍曆TreeView並尋找和選定節點

來源:互聯網
上載者:User

首先先看一段MSDN上的樣本程式:列印一個樹中所有節點名稱

MSDN上遍曆樹節點的樣本程式
 1private void PrintRecursive(TreeNode treeNode)
 2{
 3    // Print the node.
 4    System.Diagnostics.Debug.WriteLine(treeNode.Text);
 5    MessageBox.Show(treeNode.Text);
 6    // Print each node recursively.
 7    foreach (TreeNode tn in treeNode.Nodes)
 8    {
 9        PrintRecursive(tn);
10    }
11}
12
13// Call the procedure using the TreeView.
14private void CallRecursive(TreeView treeView)
15{
16    // Print each node recursively.
17    TreeNodeCollection nodes = treeView.Nodes;
18    foreach (TreeNode n in nodes)
19    {
20        PrintRecursive(n);
21    }
22}

 

然後要說明的是一下TreeView類和TreeNode類之間的關係:TreeView類中有個唯讀屬性是Nodes,它是屬於TreeNodeCollection類型的,而對於一個TreeView它的Nodes屬性就是返回treeView根結點的集合。

然後就是我的遞迴遍曆尋找一個樹節點的方法(由於程式需要我是根據樹節點的ImageIndex屬性尋找的):

Code
private TreeNode FindTreeNode(int imageIndex, TreeNode tnParent)
{
    if (tnParent == null)
        return null;
    if (tnParent.ImageIndex == imageIndex)
        return tnParent;
    TreeNode tnRet = null;
    foreach (TreeNode tn in tnParent.Nodes)
    {
        tnRet = FindTreeNode(imageIndex, tn);
        if (tnRet != null)
            break;
    }
    return tnRet;
}

private TreeNode CallFindNode(int imageIndex, TreeView treeView)
{
    TreeNodeCollection nodes = treeView.Nodes;
    foreach (TreeNode n in nodes)
    {
        TreeNode temp = FindTreeNode(imageIndex, n);
        if (temp != null)
            return temp;
    }
    return null;
}

/// <summary>
/// 這個是一個點擊事件,其中改變了選中節點,
/// 改變選中節點的同時就觸發了selectedNodeChanged事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void myControlTransactions_AddCustomer(object sender, EventArgs e)
{
    TreeNode temp = CallFindNode(3, treeView1);
    if (temp != null)
        treeView1.SelectedNode = temp;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.