クリックして評価とフィードバックをお寄せください
MSDN
MSDN ライブラリ
.NET 開発
.NET Framework 3.5
.NET Framework 3.5
System.Windows.Forms 名前空間
TreeView クラス

  低帯域幅での表示をオンにする
このページは次のバージョンについて記述しています。
Microsoft Visual Studio 2008/.NET Framework 3.5

その他のバージョンについては、以下の情報を参照してください。
.NET Framework クラス ライブラリ
TreeView クラス

更新 : 2007 年 11 月

それぞれが TreeNode で表される、ラベル付けされた項目の階層コレクションを表示します。

名前空間 :  System.Windows.Forms
アセンブリ :  System.Windows.Forms (System.Windows.Forms.dll 内)

Visual Basic (宣言)
<ComVisibleAttribute(True)> _
<DockingAttribute(DockingBehavior.Ask)> _
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
Public Class TreeView _
    Inherits Control
Visual Basic (使用法)
Dim instance As TreeView
C#
[ComVisibleAttribute(true)]
[DockingAttribute(DockingBehavior.Ask)]
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)]
public class TreeView : Control
Visual C++
[ComVisibleAttribute(true)]
[DockingAttribute(DockingBehavior::Ask)]
[ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)]
public ref class TreeView : public Control
J#
/** @attribute ComVisibleAttribute(true) */
/** @attribute DockingAttribute(DockingBehavior.Ask) */
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */
public class TreeView extends Control
JScript
public class TreeView extends Control

Nodes コレクションには、TreeView コントロールに割り当てられているすべての TreeNode オブジェクトが格納されます。このコレクション内のツリー ノードは、ルート ツリー ノードと呼ばれます。続けてルート ツリー ノードに追加されたツリー ノードは、子ノードと呼ばれます。各 TreeNode には、他の TreeNode オブジェクトのコレクションを含めることができるため、コレクションを反復処理するときにツリー構造内の位置がわからなくなる場合があります。TreeNode..::.FullPath 文字列を解析するときに PathSeparator 文字列値を使用すると、1 つの TreeNode ラベルがどこから始まってどこで終わっているかがわかります。

ツリー ノードの横にイメージを表示するには、ImageListImageList プロパティに割り当て、ImageList 内の Image のインデックス値を参照することによって、そのImage を割り当てます。イメージを割り当てるには次のプロパティを使用します。

  • ImageIndex プロパティには、ツリー ノードが選択されていないときに表示する Image のインデックス値を設定します。

  • SelectedImageIndex プロパティには、ツリー ノードが選択されているときに表示する Image のインデックス値を設定します。

ImageIndex プロパティ値と SelectedImageIndex プロパティ値によって参照されるイメージは、Nodes コレクションに割り当てられているすべてのツリー ノードで表示される既定のイメージです。各ツリー ノードでは、TreeNode..::.ImageIndex プロパティと TreeNode..::.SelectedImageIndex プロパティを設定することで、この既定のイメージをオーバーライドできます。

ツリー ノードを展開して、その次のレベルにある子ツリー ノードを表示できます。TreeNode の横にプラス記号 (+) ボタンが表示されている場合は、ユーザーがそのボタンをクリックすると、TreeNode が展開されます。または、TreeNode..::.Expand メソッドを呼び出した場合も、TreeNode が展開されます。Nodes コレクション内のすべての子ツリー ノードを展開するには、ExpandAll メソッドを呼び出します。子レベルの TreeNode を折りたたむには、TreeNode..::.Collapse メソッドを呼び出します。または、TreeNode の横にマイナス記号 (-) ボタンが表示されている場合は、ユーザーがそのボタンを押すと折りたたまれます。TreeNode..::.Toggle メソッドを呼び出して、ノードが展開された状態と折りたたまれた状態を切り替えることもできます。

ツリー ノードには、オプションでチェック ボックスを表示できます。チェック ボックスを表示するには、TreeViewCheckBoxes プロパティを true に設定します。チェックされた状態のツリー ノードについては、Checked プロパティが true に設定されます。

メモ :

TreeNode..::.Checked プロパティを BeforeCheck イベント内または AfterCheck イベント内から設定すると、イベントが複数回発生することになり、予期できない動作を引き起こす可能性があります。たとえば、子ノードを再帰的に更新するときは、イベント ハンドラで Checked プロパティを設定することによって、ユーザーは各ノードを展開してチェックする必要がなくなります。イベントが複数回発生することを防ぐためには、TreeViewEventArgsAction プロパティが TreeViewAction..::.Unknown に設定されていない場合に、再帰コードだけを実行するロジックをイベント ハンドラに追加します。この方法の例については、AfterCheck イベントまたは BeforeCheck イベントのトピックの例を参照してください。

表示プロパティとスタイル プロパティをいくつか設定すると、TreeView コントロールの外観を変更できます。ShowPlusMinustrue に設定すると、各 TreeNode の横にプラス記号ボタンかマイナス記号ボタンが表示され、それぞれのボタンでそのノードを展開したり、折りたたんだりできます。ShowRootLines プロパティを true に設定すると、TreeView には、すべてのルート ツリー ノードを結合する線が表示されます。子ツリー ノードとそのルート ノードを結合する線を表示するには、ShowLines プロパティを true に設定します。HotTracking プロパティを true に設定すると、ツリー ノードのラベル上にマウス ポインタが配置されたときにそのラベルの外観が変わります。HotTracking プロパティが設定されると、ツリー ノード ラベルの外観がハイパーリンクになります。また、TreeView コントロールの外観を完全にカスタマイズすることもできます。この操作を実行するには、DrawMode プロパティを TreeViewDrawMode..::.Normal 以外の値に設定し、DrawNode イベントを処理します。

メモ :

実行時に CheckBoxesScrollableImageIndexSelectedImageIndex の各プロパティを設定すると、TreeView ハンドルが再作成され (Control..::.RecreateHandle のトピックを参照)、コントロールの外観が更新されます。これによって、選択されている TreeNode を除くすべてのツリー ノードの表示が折りたたまれます。

TreeView コントロールの使用方法を示すコード例を次に示します。

Visual Basic
' Populates a TreeView control with example nodes. 
Private Sub InitializeTreeView()
    treeView1.BeginUpdate()
    treeView1.Nodes.Add("Parent")
    treeView1.Nodes(0).Nodes.Add("Child 1")
    treeView1.Nodes(0).Nodes.Add("Child 2")
    treeView1.Nodes(0).Nodes(1).Nodes.Add("Grandchild")
    treeView1.Nodes(0).Nodes(1).Nodes(0).Nodes.Add("Great Grandchild")
    treeView1.EndUpdate()
End Sub

C#
// Populates a TreeView control with example nodes. 
private void InitializeTreeView()
{
    treeView1.BeginUpdate();
    treeView1.Nodes.Add("Parent");
    treeView1.Nodes[0].Nodes.Add("Child 1");
    treeView1.Nodes[0].Nodes.Add("Child 2");
    treeView1.Nodes[0].Nodes[1].Nodes.Add("Grandchild");
    treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Great Grandchild");
    treeView1.EndUpdate();
}

TreeView コントロールに顧客情報を表示する、より複雑なコード例を次に示します。ルート ツリー ノードに顧客名が表示され、各顧客に割り当てられた発注番号が子ツリー ノードに表示されます。この例では、1,000 人の顧客が表示され、顧客ごとに 15 の発注内容が示されます。BeginUpdate メソッドと EndUpdate メソッドを使用すると、TreeView は再描画されません。TreeViewTreeNode オブジェクトを作成して描画する間、待機 Cursor が表示されます。この例では、Order オブジェクトのコレクションを保持できる Customer オブジェクトが存在する必要があります。また、MyWait.cur という名前のカーソル ファイルがアプリケーション ディレクトリにあり、TreeView コントロールのインスタンスを Form 上に作成済みであることも前提にしています。

Visual Basic
Public Class Customer
   Inherits [Object]
   Private custName As String = ""
   Friend custOrders As New ArrayList()

   Public Sub New(ByVal customername As String)
      Me.custName = customername
   End Sub

   Public Property CustomerName() As String
      Get
         Return Me.custName
      End Get
      Set(ByVal Value As String)
         Me.custName = Value
      End Set
   End Property

   Public ReadOnly Property CustomerOrders() As ArrayList
      Get
         Return Me.custOrders
      End Get
   End Property
End Class 'End Customer class


Public Class Order
   Inherits [Object]
   Private ordID As String

   Public Sub New(ByVal orderid As String)
      Me.ordID = orderid
   End Sub 'New

   Public Property OrderID() As String
      Get
         Return Me.ordID
      End Get
      Set(ByVal Value As String)
         Me.ordID = Value
      End Set
   End Property
End Class ' End Order class

' Create a new ArrayList to hold the Customer objects.
Private customerArray As New ArrayList()

Private Sub FillMyTreeView()
   ' Add customers to the ArrayList of Customer objects.
   Dim x As Integer
   For x = 0 To 999
      customerArray.Add(New Customer("Customer" + x.ToString()))
   Next x

   ' Add orders to each Customer object in the ArrayList.
   Dim customer1 As Customer
   For Each customer1 In customerArray
      Dim y As Integer
      For y = 0 To 14
         customer1.CustomerOrders.Add(New Order("Order" + y.ToString()))
      Next y
   Next customer1

   ' Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = New Cursor("MyWait.cur")

   ' Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate()

   ' Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear()

   ' Add a root TreeNode for each Customer object in the ArrayList.
   Dim customer2 As Customer
   For Each customer2 In customerArray
      treeView1.Nodes.Add(New TreeNode(customer2.CustomerName))

      ' Add a child TreeNode for each Order object in the current Customer object.
      Dim order1 As Order
      For Each order1 In customer2.CustomerOrders
         treeView1.Nodes(customerArray.IndexOf(customer2)).Nodes.Add( _
    New TreeNode(customer2.CustomerName + "." + order1.OrderID))
      Next order1
   Next customer2

   ' Reset the cursor to the default for all controls.
   Cursor.Current = System.Windows.Forms.Cursors.Default

   ' Begin repainting the TreeView.
   treeView1.EndUpdate()
End Sub 'FillMyTreeView

C#
// The basic Customer class.
public class Customer : System.Object
{
   private string custName = "";
   protected ArrayList custOrders = new ArrayList();

   public Customer(string customername)
   {
      this.custName = customername;
   }

   public string CustomerName
   {      
      get{return this.custName;}
      set{this.custName = value;}
   }

   public ArrayList CustomerOrders 
   {
      get{return this.custOrders;}
   }

} // End Customer class 


// The basic customer Order class.
public class Order : System.Object
{
   private string ordID = "";

   public Order(string orderid)
   {
      this.ordID = orderid;
   }

   public string OrderID
   {      
      get{return this.ordID;}
      set{this.ordID = value;}
   }

} // End Order class

// Create a new ArrayList to hold the Customer objects.
private ArrayList customerArray = new ArrayList(); 

private void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for(int x=0; x<1000; x++)
   {
      customerArray.Add(new Customer("Customer" + x.ToString()));
   }

   // Add orders to each Customer object in the ArrayList.
   foreach(Customer customer1 in customerArray)
   {
      for(int y=0; y<15; y++)
      {
         customer1.CustomerOrders.Add(new Order("Order" + y.ToString()));    
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   Cursor.Current = new Cursor("MyWait.cur");

   // Suppress repainting the TreeView until all the objects have been created.
   treeView1.BeginUpdate();

   // Clear the TreeView each time the method is called.
   treeView1.Nodes.Clear();

   // Add a root TreeNode for each Customer object in the ArrayList.
   foreach(Customer customer2 in customerArray)
   {
      treeView1.Nodes.Add(new TreeNode(customer2.CustomerName));

      // Add a child treenode for each Order object in the current Customer object.
      foreach(Order order1 in customer2.CustomerOrders)
      {
         treeView1.Nodes[customerArray.IndexOf(customer2)].Nodes.Add(
           new TreeNode(customer2.CustomerName + "." + order1.OrderID));
      }
   }

   // Reset the cursor to the default for all controls.
   Cursor.Current = Cursors.Default;

   // Begin repainting the TreeView.
   treeView1.EndUpdate();
}

Visual C++
// The basic Customer class.
ref class Customer: public System::Object
{
private:
   String^ custName;

protected:
   ArrayList^ custOrders;

public:
   Customer( String^ customername )
   {
      custName = "";
      custOrders = gcnew ArrayList;
      this->custName = customername;
   }


   property String^ CustomerName 
   {
      String^ get()
      {
         return this->custName;
      }

      void set( String^ value )
      {
         this->custName = value;
      }

   }

   property ArrayList^ CustomerOrders 
   {
      ArrayList^ get()
      {
         return this->custOrders;
      }

   }

};


// End Customer class
// The basic customer Order class.
ref class Order: public System::Object
{
private:
   String^ ordID;

public:
   Order( String^ orderid )
   {
      ordID = "";
      this->ordID = orderid;
   }


   property String^ OrderID 
   {
      String^ get()
      {
         return this->ordID;
      }

      void set( String^ value )
      {
         this->ordID = value;
      }

   }

};
// End Order class



void FillMyTreeView()
{
   // Add customers to the ArrayList of Customer objects.
   for ( int x = 0; x < 1000; x++ )
   {
      customerArray->Add( gcnew Customer( "Customer " + x ) );
   }

   // Add orders to each Customer object in the ArrayList.
   IEnumerator^ myEnum = customerArray->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Customer^ customer1 = safe_cast<Customer^>(myEnum->Current);
      for ( int y = 0; y < 15; y++ )
      {
         customer1->CustomerOrders->Add( gcnew Order( "Order " + y ) );
      }
   }

   // Display a wait cursor while the TreeNodes are being created.
   ::Cursor::Current = gcnew System::Windows::Forms::Cursor( "MyWait.cur" );

   // Suppress repainting the TreeView until all the objects have been created.
   treeView1->BeginUpdate();

   // Clear the TreeView each time the method is called.
   treeView1->Nodes->Clear();

   // Add a root TreeNode for each Customer object in the ArrayList.
   myEnum = customerArray->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Customer^ customer2 = safe_cast<Customer^>(myEnum->Current);
      treeView1->Nodes->Add( gcnew TreeNode( customer2->CustomerName ) );

      // Add a child treenode for each Order object in the current Customer object.
      IEnumerator^ myEnum = customer2->CustomerOrders->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Order^ order1 = safe_cast<Order^>(myEnum->Current);
         treeView1->Nodes[ customerArray->IndexOf( customer2 ) ]->Nodes->Add( gcnew TreeNode( customer2->CustomerName + "." + order1->OrderID ) );
      }
   }

   // Reset the cursor to the default for all controls.
   ::Cursor::Current = Cursors::Default;

   // Begin repainting the TreeView.
   treeView1->EndUpdate();
}

J#
// The basic Customer class.
public class Customer extends Object
{
    private String custName = "";
    protected ArrayList custOrders = new ArrayList();

    public Customer(String customername)
    {
        this.custName = customername;
    } //Customer

    /** @property 
     */
    public String get_CustomerName()
    {
        return this.custName;
    } //get_CustomerName

    /** @property 
     */
    public void set_CustomerName(String value)
    {
        this.custName = value;
    } //set_CustomerName

    /** @property 
     */
    public ArrayList get_CustomerOrders()
    {
        return this.custOrders;
    } //get_CustomerOrders
} //End Customer class

// The basic customer Order class.
public class Order extends Object
{
    private String ordID = "";

    public Order(String orderid)
    {
        this.ordID = orderid;
    } //Order

    /** @property 
     */
    public String get_OrderID()
    {
        return this.ordID;
    } //get_OrderID

    /** @property 
     */
    public void set_OrderID(String value)
    {
        this.ordID = value;
    } //set_OrderID
} // End Order class

// Create a new ArrayList to hold the Customer objects.
private ArrayList customerArray = new ArrayList();

private void FillMyTreeView()
{
    // Add customers to the ArrayList of Customer objects.
    for (int x = 0; x < 1000; x++) {
        customerArray.Add(new Customer("Customer"
            + ((Int32)x).ToString()));
    }
    // Add orders to each Customer object in the ArrayList.
    for (int iCtr = 0; iCtr < customerArray.get_Count(); iCtr++) {
        Customer customer1 = (Customer)customerArray.get_Item(iCtr);
        for (int y = 0; y < 15; y++) {
            customer1.get_CustomerOrders().Add(new Order("Order"
                + ((Int32)y).ToString()));
        }
    }
    // Display a wait cursor while the TreeNodes are being created.
    get_Cursor().set_Current(new Cursor("MyWait.cur"));
    // Suppress repainting the TreeView until all the objects have
    // been created.
    treeView1.BeginUpdate();
    // Clear the TreeView each time the method is called.
    treeView1.get_Nodes().Clear();
    // Add a root TreeNode for each Customer object in the ArrayList.
    for (int iCtr1 = 0; iCtr1 < customerArray.get_Count(); iCtr1++) {
        Customer customer2 = (Customer)customerArray.get_Item(iCtr1);
        treeView1.get_Nodes().Add(new TreeNode(customer2.get_CustomerName()));
        // Add a child treenode for each Order object in the current
        // Customer object.
        for (int iCtr2 = 0; iCtr2 < customer2.get_CustomerOrders().
            get_Count(); iCtr2++) {
            Order order1 = (Order)customer2.get_CustomerOrders().
                get_Item(iCtr2);
            treeView1.get_Nodes().
                get_Item(customerArray.IndexOf(customer2)).get_Nodes().
                Add(new TreeNode(customer2.get_CustomerName() + "."
                + order1.get_OrderID()));
        }
    }
    // Reset the cursor to the default for all controls.
    get_Cursor().set_Current(Cursors.get_Default());
    // Begin repainting the TreeView.
    treeView1.EndUpdate();
} //FillMyTreeView

この型のすべてのパブリック static (Visual Basic では Shared) メンバは、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

.NET Framework および .NET Compact Framework では、各プラットフォームのすべてのバージョンはサポートしていません。サポートされているバージョンについては、「.NET Framework システム要件」を参照してください。

.NET Framework

サポート対象 : 3.5、3.0、2.0、1.1、1.0

.NET Compact Framework

サポート対象 : 3.5、2.0、1.0
コミュニティ コンテンツ   コミュニティ コンテンツとは
新しいコンテンツの追加 RSS  注釈
Processing
© 2009 Microsoft Corporation. All rights reserved. 使用条件  |  商標  |  プライバシー
Page view tracker