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

傳回

項目之以零起始的索引,樹狀節點集合中找到,否則為 -1。

範例

下列程式碼範例會判斷指定的 TreeNode 是否在 內 TreeNodeCollection ,然後列舉集合。 此範例會要求您具有 FormTreeNodeCollectionTreeView 且具有包含 TreeNode 具名 myTreeNode2 的 。

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 寫 類別的 方法來自訂衍生 TreeNode 型別的 TreeNode 這個方法行為。

適用於