TreeNodeCollection.IndexOf(TreeNode) 方法

定义

返回集合中指定树节点的索引。

public:
 int IndexOf(System::Windows::Forms::TreeNode ^ node);
public int IndexOf (System.Windows.Forms.TreeNode node);
member this.IndexOf : System.Windows.Forms.TreeNode -> int
Public Function IndexOf (node As TreeNode) As Integer

参数

node
TreeNode

要在集合中查找的 TreeNode

返回

Int32

树节点集合中项的从零开始的索引;否则为 -1。

示例

下面的代码示例确定指定 TreeNode 是否在集合 TreeNodeCollection中,然后枚举集合。 本示例要求你具有一个FormTreeView包含已命名myTreeNode2名称的TreeNodeTreeNodeCollection

void EnumerateTreeNodes()
{
   TreeNodeCollection^ myNodeCollection = myTreeView->Nodes;

   // Check for a node in the collection.
   if ( myNodeCollection->Contains( myTreeNode2 ) )
   {
      myLabel->Text = myLabel->Text + "Node2 is at index: " + myNodeCollection->IndexOf( myTreeNode2 );
   }

   myLabel->Text = myLabel->Text + "\n\nElements of the TreeNodeCollection:\n";

   // Create an enumerator for the collection.
   IEnumerator^ myEnumerator = myNodeCollection->GetEnumerator();
   while ( myEnumerator->MoveNext() )
   {
      myLabel->Text = myLabel->Text + (dynamic_cast<TreeNode^>(myEnumerator->Current))->Text + "\n";
   }
}
private void EnumerateTreeNodes()
{
   TreeNodeCollection myNodeCollection = myTreeView.Nodes;
   // Check for a node in the collection.
   if (myNodeCollection.Contains(myTreeNode2))
   {
      myLabel.Text += "Node2 is at index: " + myNodeCollection.IndexOf(myTreeNode2);
   }
   myLabel.Text += "\n\nElements of the TreeNodeCollection:\n";

   // Create an enumerator for the collection.
   IEnumerator myEnumerator = myNodeCollection.GetEnumerator();
   while(myEnumerator.MoveNext())
   {
      myLabel.Text += ((TreeNode)myEnumerator.Current).Text +"\n";
   }
}
Private Sub EnumerateTreeNodes()
   Dim myNodeCollection As TreeNodeCollection = myTreeView.Nodes
   ' Check for a node in the collection.
   If myNodeCollection.Contains(myTreeNode2) Then
      myLabel.Text += "Node2 is at index: " + myNodeCollection.IndexOf(myTreeNode2)
   End If
   myLabel.Text += ControlChars.Cr + ControlChars.Cr + _
     "Elements of the TreeNodeCollection:" + ControlChars.Cr
   
   ' Create an enumerator for the collection.
   Dim myEnumerator As IEnumerator = myNodeCollection.GetEnumerator()
   While myEnumerator.MoveNext()
      myLabel.Text += CType(myEnumerator.Current, TreeNode).Text + ControlChars.Cr
   End While
End Sub

注解

此方法花费的时间量与节点集合的大小成正比,因此可能需要避免将它与大型集合一起使用。

此方法仅检查引用相等性。 不能使用它检索集合中等效但不同节点的索引。

备注

引用相等要求的一个含义是,不能通过重写Equals类的方法TreeNodeTreeNode自定义此方法的行为。

适用于