TreeView クラスとは? わかりやすく解説

TreeView クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

目次などの階層データツリー構造表示します

名前空間: System.Web.UI.WebControls
アセンブリ: System.Web (system.web.dll 内)
構文構文

<ControlValuePropertyAttribute("SelectedValue")>
 _
Public Class TreeView
    Inherits HierarchicalDataBoundControl
    Implements IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler
[ControlValuePropertyAttribute("SelectedValue")] 
public class TreeView : HierarchicalDataBoundControl,
 IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler
[ControlValuePropertyAttribute(L"SelectedValue")] 
public ref class TreeView : public
 HierarchicalDataBoundControl, IPostBackEventHandler, IPostBackDataHandler, ICallbackEventHandler
/** @attribute ControlValuePropertyAttribute("SelectedValue") */ 
public class TreeView extends HierarchicalDataBoundControl
 implements IPostBackEventHandler, IPostBackDataHandler, 
    ICallbackEventHandler
ControlValuePropertyAttribute("SelectedValue") 
public class TreeView extends
 HierarchicalDataBoundControl implements IPostBackEventHandler, IPostBackDataHandler,
 
    ICallbackEventHandler
解説解説

TreeView コントロールは、目次ファイル ディレクトリなどの階層データツリー構造表示する場合使用され次の機能サポートします

ノード

TreeView コントロールノード構成されます。ツリー内の各エントリはノード呼ばれ、TreeNode オブジェクト表されます。ノード型は次のように定義されます。

ノードは、親と子両方該当することがあります。ただし、1 つノードルート ノード親ノード、および葉ノード兼ねることはありません。ノード表示動作に関する一部プロパティは、ノードルート、親、のどのノード該当するかによって決定されます。

通常のツリー構造にはルート ノード1 つしかありませんが、TreeView コントロール使用すると、ツリー構造複数ルート ノード追加できます。この機能は、製品カテゴリ一覧のように 1 つルート ノード表示せずに項目一覧表示する場合に便利です。

ノードには、Text プロパティValue プロパティありますノード関連付けられているポストバック イベント渡されるデータなど、ノードに関する補足データ格納するために Value プロパティ使用されている間、Text プロパティの値は TreeView表示されます。

ノード選択モードまたはナビゲーション モードいずれかになります既定では、ノード選択モードになってます。ノードナビゲーション モードにするには、ノードの NavigateUrl プロパティを、空の文字列 ("") 以外の値に設定しますノード選択モードにするには、ノードNavigateUrl プロパティ空の文字列 ("") に設定します

静的データ
データへのバインド

TreeView コントロールデータバインドすることもできますTreeView コントロール適切なデータ ソース種類バインドするには、次の 2 つメソッドいずれか使用します

複数属性を持つ XML 要素どのように、各データ項目に複数プロパティ含まれているデータ ソースバインドする場合ノードにはデータ項目の ToString メソッドから返される値が既定表示されます。XML 要素場合ノードには要素名が表示されます。これはメニュー ツリーの基になる構造体を示す以外はあまり用途はありません。DataBindings コレクション使用してツリー ノードバインディング指定することにより、ノード特定のデータ項目のプロパティバインドできますDataBindings コレクションには、データ項目とそのバインド先のノードとの間の関係を定義する TreeNodeBinding オブジェクト含まれています。バインディング基準、およびノード表示するデータ項目のプロパティ指定できますツリー ノードバインディング詳細については、TreeNodeBinding のトピック参照してください

セキュリティに関するメモメモ

LevelStyles コレクション使用して特定の深さレベルに対してスタイル定義されている場合、そのスタイルは、その深さにあるノードすべてのルート親ノード、または葉ノードスタイル設定オーバーライドます。

別の方法コントロール外観変更するには、TreeView コントロール表示されるイメージカスタマイズます。次の表に示されているプロパティ設定してコントロール部分ごとにの独自の一連のカスタム イメージ指定できます

TreeView コントロール使用すると、ノードの隣にチェック ボックス表示することもできます。ShowCheckBoxes プロパティTreeNodeTypes.None 以外の値に設定すると、指定したノード型の隣にチェック ボックス表示されます。

メモメモ

ShowCheckBoxes プロパティは、TreeNodeTypes 列挙型メンバ値のビットごとの組み合わせ設定できます

ページサーバーポストするたびに、CheckedNodes コレクションには選択したノード自動的に設定されます。チェック ボックス表示されている場合、TreeNodeCheckChanged イベント使用してサーバーへの各ポストの間にチェック ボックスの状態が変更されるたびにカスタム ルーチン実行できます

イベント

TreeView コントロールには、プログラム利用できる複数イベント用意されています。これにより、イベント発生するたびにカスタム ルーチン実行されるようにできますTreeView コントロールサポートされイベントの一覧を次の表に示します

イベント

説明

TreeNodeCheckChanged

TreeView コントロールチェック ボックスの状態がサーバーへの各ポストの間に変更され場合発生します

SelectedNodeChanged

TreeView コントロールノード選択されたときに発生します

TreeNodeExpanded

TreeView コントロールノード展開されたときに発生します

TreeNodeCollapsed

TreeView コントロールノード折りたたまれたときに発生します

TreeNodePopulate

PopulateOnDemand プロパティtrue設定されているノードTreeView コントロール展開されたときに発生します

TreeNodeDataBound

TreeView コントロールデータ項目がノードバインドされたときに発生します

ユーザー補助

スクロール
TopicLocation
チュートリアル : TreeView コントロールでの階層データ表示Visual Studio での ASP .NET Web アプリケーション作成
チュートリアル : Web サイトへのサイト ナビゲーション追加Visual Studio での ASP .NET Web アプリケーション作成
チュートリアル : セキュリティ ロールに基づくサイトマップ ノードフィルタ処理Visual Studio での ASP .NET Web アプリケーション作成
チュートリアル : テーマ使用した Web サイトカスタマイズVisual Studio での ASP .NET Web アプリケーション作成
方法 : ASP.NETサイト マップ プロバイダ実装するASP .NET Web アプリケーション作成
方法 : SiteMapDataSource Web サーバー コントロールによって取得されノードフィルタ処理するASP .NET Web アプリケーション作成
方法 : SiteMapPath Web サーバー コントロール外観カスタマイズするASP .NET Web アプリケーション作成
方法 : TreeView のノード要素追加または削除する (Visual Studio)Visual Studio での ASP .NET Web アプリケーション作成
方法 : サイトマップ ノードコードによって列挙するASP .NET Web アプリケーション作成
方法 : 簡単なサイト ナビゲーション追加するASP .NET Web アプリケーション作成
方法 : 複数サイト マップサイトマップ プロバイダ設定するASP .NET Web アプリケーション作成
方法 : 非階層 Web Server コントロール内にサイト マップ データ表示するASP .NET Web アプリケーション作成
使用例使用例

このセクションには、7 つコード例含まれています。

次のコード例に対してフレーム設定する方法次のコード例示します

<html>
         
    <frameset cols="30%, 75%">
   
        <frame name="Menu" src="TreeViewFramevb.aspx"/>
        <frame name="Content" src="Home.aspx"/>
 
           
    </frameset>      
   
</html>

<html>
         
    <frameset cols="30%, 75%">
   
        <frame name="Menu" src="TreeViewFramecs.aspx"/>
        <frame name="Content" src="Home.aspx"/> 
           
    </frameset>      
   
</html>

宣言構文使用して TreeView コントロール静的データ表示する方法次のコード例示します。この例は、前の例のフレームセット内に目次を表すために使用されます。

<%@ Page Language="VB" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView Declarative Syntax Example</h3>
      
      <asp:TreeView id="SampleTreeView" 
        runat="server">
         
        <Nodes>
        
          <asp:TreeNode Value="Home" 
            NavigateUrl="Home.aspx" 
            Text="Home"
            Target="Content" 
            Expanded="True">
             
            <asp:TreeNode Value="Page 1" 
              NavigateUrl="Page1.aspx" 
              Text="Page1"
              Target="Content">
               
              <asp:TreeNode Value="Section 1" 
                NavigateUrl="Section1.aspx" 
                Text="Section 1"
                Target="Content"/>
                 
            </asp:TreeNode>              
            
            <asp:TreeNode Value="Page 2" 
              NavigateUrl="Page2.aspx"
              Text="Page 2"
              Target="Content">
               
            </asp:TreeNode> 
            
          </asp:TreeNode>
        
        </Nodes>
        
      </asp:TreeView>

    </form>
  </body>
</html>

<%@ Page Language="C#" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView Declarative Syntax Example</h3>
      
      <asp:TreeView id="SampleTreeView" 
        runat="server">
         
        <Nodes>
        
          <asp:TreeNode Value="Home" 
            NavigateUrl="Home.aspx" 
            Text="Home"
            Target="Content" 
            Expanded="True">
             
            <asp:TreeNode Value="Page 1" 
              NavigateUrl="Page1.aspx" 
              Text="Page1"
              Target="Content">
               
              <asp:TreeNode Value="Section 1" 
                NavigateUrl="Section1.aspx" 
                Text="Section 1"
                Target="Content"/>
                 
            </asp:TreeNode>              
            
            <asp:TreeNode Value="Page 2" 
              NavigateUrl="Page2.aspx"
              Text="Page 2"
              Target="Content">
               
            </asp:TreeNode> 
            
          </asp:TreeNode>
        
        </Nodes>
        
      </asp:TreeView>

    </form>
  </body>
</html>

TreeView コントロールXML データ ソースバインドする方法次のコード例示します。この例を正常に動作させるには、このコード例の後に示すサンプル XML データを、Book.xml という名前のファイルコピーする必要があります

<%@ Page Language="VB" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView XML Data Binding Example</h3>
    
      <asp:TreeView id="BookTreeView" 
        DataSourceID=BookXmlDataSource
        runat="server">
         
        <DataBindings>
          <asp:TreeNodeBinding DataMember="Book"
 TextField="Title"/>
          <asp:TreeNodeBinding DataMember="Chapter"
 TextField="Heading"/>
          <asp:TreeNodeBinding DataMember="Section"
 TextField="Heading"/>
        </DataBindings>
         
      </asp:TreeView>

      <asp:XmlDataSource id="BookXmlDataSource"
  
        DataFile="Book.xml"
        runat="server">
      </asp:XmlDataSource>
    
    </form>
  </body>
</html>

<%@ Page Language="C#" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView XML Data Binding Example</h3>
    
      <asp:TreeView id="BookTreeView" 
        DataSourceID=BookXmlDataSource
        runat="server">
         
        <DataBindings>
          <asp:TreeNodeBinding DataMember="Book" TextField="Title"/>
          <asp:TreeNodeBinding DataMember="Chapter" TextField="Heading"/>
          <asp:TreeNodeBinding DataMember="Section" TextField="Heading"/>
        </DataBindings>
         
      </asp:TreeView>

      <asp:XmlDataSource id="BookXmlDataSource"  
        DataFile="Book.xml"
        runat="server">
      </asp:XmlDataSource>
    
    </form>
  </body>
</html>

前の例に対応したサンプル XML データ次のコード例示します

<Book Title="Book Title">
    <Chapter Heading="Chapter 1">
        <Section Heading="Section 1">
        </Section>
        <Section Heading="Section 2">
        </Section>
    </Chapter>
    <Chapter Heading="Chapter 2">
        <Section Heading="Section 1">
        </Section>
    </Chapter>
</Book>

TreeView コントロールSiteMapDataSource コントロールバインドしてサイト ナビゲーション使用する方法次のコード例示します。この例を正常に動作させるには、このコード例の後に示すサンプル サイト マップ データを、Web.sitemap という名前のファイルコピーする必要があります

<%@ Page Language="VB" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView AutoGenerateBindings Example</h3>
    
      <!-- Set the AutoGenerateBindings property
 -->
      <!-- to false declaratively to
 allow for   -->
      <!-- the user-defined Bindings collection. -->
      <asp:TreeView id="SiteTreeView" 
        DataSourceID="SiteMapSource"
        AutoGenerateDataBindings="False"
        runat="server">
        
        <DataBindings>
        
          <asp:TreeNodeBinding TextField="title"
 NavigateUrlField="url"/>
        
        </DataBindings>
            
      </asp:TreeView>
      
      <asp:SiteMapDataSource ID="SiteMapSource"
 runat="server"/>
         
    </form>
  </body>
</html>

<%@ Page Language="C#" %>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView AutoGenerateBindings Example</h3>
    
      <!-- Set the AutoGenerateBindings property -->
      <!-- to false declaratively to allow for
   -->
      <!-- the user-defined Bindings collection. -->
      <asp:TreeView id="SiteTreeView" 
        DataSourceID="SiteMapSource"
        AutoGenerateDataBindings="False"
        runat="server">
        
        <DataBindings>
        
          <asp:TreeNodeBinding TextField="title" NavigateUrlField="url"/>
        
        </DataBindings>
            
      </asp:TreeView>
      
      <asp:SiteMapDataSource ID="SiteMapSource" runat="server"/>
         
    </form>
  </body>
</html>

前のコード例対応したサンプル サイト マップ データ次のコード例示します

<siteMap>
    <siteMapNode title="Home" description="Home" url="default.aspx">
        <siteMapNode title="Products" description="Products" url="Products.aspx">
            <siteMapNode title="Computers" url="Computers.aspx"/>
            <siteMapNode title="Accessories" url="Accessories.aspx"/>     
        </siteMapNode>
    </siteMapNode>
</siteMap>

TreeView コントロールノードクライアントの値を設定する方法次のコード例示しますクライアント側ノードへのデータ設定有効な場合サーバーポスト バックしなくても、クライアントノード動的にデータ設定されます。

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data"
 %>
<%@ Import Namespace="System.Data.SqlClient"
 %>

<script runat="server">

  Sub PopulateNode(ByVal sender As
 Object, ByVal e As TreeNodeEventArgs)

    ' Call the appropriate method to populate a node at a particular
 level.
    Select Case e.Node.Depth

      Case 0
        ' Populate the first-level nodes.
        PopulateCategories(e.Node)

      Case 1
        ' Populate the second-level nodes.
        PopulateProducts(e.Node)

      Case Else
        ' Do nothing.

    End Select

  End Sub

  Sub PopulateCategories(ByVal node As
 TreeNode)

    ' Query for the product categories. These are the values
    ' for the second-level nodes.
    Dim ResultSet As DataSet = RunQuery("Select
 CategoryID, CategoryName From Categories")

    ' Create the second-level nodes.
    If ResultSet.Tables.Count > 0 Then

      ' Iterate through and create a new node for each row in the query
 results.
      ' Notice that the query results are stored in the table of the
 DataSet.
      Dim row As DataRow

      For Each row In ResultSet.Tables(0).Rows

        ' Create the new node. Notice that the CategoryId is stored
 in the Value property 
        ' of the node. This will make querying for items in a specific
 category easier when
        ' the third-level nodes are created. 
        Dim newNode As TreeNode = New
 TreeNode()
        Newnode.Text = row("CategoryName").ToString()
 
        Newnode.Value = row("CategoryID").ToString()

        ' Set the PopulateOnDemand property to true so that the child
 nodes can be 
        ' dynamically populated.
        newNode.PopulateOnDemand = True

        ' Set additional properties for the node.
        newNode.SelectAction = TreeNodeSelectAction.Expand

        ' Add the new node to the ChildNodes collection of the parent
 node.
        node.ChildNodes.Add(newNode)

      Next

    End If

  End Sub

  Sub PopulateProducts(ByVal node As
 TreeNode)

    ' Query for the products of the current category. These are the
 values
    ' for the third-level nodes.
    Dim ResultSet As DataSet = RunQuery("Select
 ProductName From Products Where CategoryID=" & node.Value)

    ' Create the third-level nodes.
    If ResultSet.Tables.Count > 0 Then

      ' Iterate through and create a new node for each row in the query
 results.
      ' Notice that the query results are stored in the table of the
 DataSet.
      Dim row As DataRow

      For Each row In ResultSet.Tables(0).Rows

        ' Create the new node.
        Dim NewNode As TreeNode = New
 TreeNode(row("ProductName").ToString())

        ' Set the PopulateOnDemand property to false, because these
 are leaf nodes and
        ' do not need to be populated.
        NewNode.PopulateOnDemand = False

        ' Set additional properties for the node.
        NewNode.SelectAction = TreeNodeSelectAction.None

        ' Add the new node to the ChildNodes collection of the parent
 node.
        node.ChildNodes.Add(NewNode)

      Next

    End If

  End Sub

  Function RunQuery(ByVal QueryString As
 String) As DataSet

    ' Declare the connection string. This example uses Microsoft SQL
 Server 
    ' and connects to the Northwind sample database.
    Dim ConnectionString As String
 = "server=localhost;database=NorthWind;Integrated Security=SSPI"

    Dim DBConnection As SqlConnection = New
 SqlConnection(ConnectionString)
    Dim DBAdapter As SqlDataAdapter
    Dim ResultsDataSet As DataSet = New
 DataSet

    Try

      ' Run the query and create a DataSet.
      DBAdapter = New SqlDataAdapter(QueryString, DBConnection)
      DBAdapter.Fill(ResultsDataSet)

      ' Close the database connection.
      DBConnection.Close()

    Catch ex As Exception

      ' Close the database connection if it is still open.
      If DBConnection.State = ConnectionState.Open Then

        DBConnection.Close()

      End If

      Message.Text = "Unable to connect to the database."

    End Try

    Return ResultsDataSet

  End Function

</script>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView PopulateNodesFromClient Example</h3>
    
      <asp:TreeView id="LinksTreeView"
        Font-Name= "Arial"
        ForeColor="Blue"
        EnableClientScript="true"
        PopulateNodesFromClient="true"  
        OnTreeNodePopulate="PopulateNode"
        runat="server">
         
        <Nodes>
        
          <asp:TreeNode Text="Inventory" 
            SelectAction="Expand"  
            PopulateOnDemand="true"/>
        
        </Nodes>
        
      </asp:TreeView>
      
      <br><br>
      
      <asp:Label id="Message" runat="server"/>

    </form>
  </body>
</html>

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">

  void PopulateNode(Object sender, TreeNodeEventArgs e)
  {

    // Call the appropriate method to populate a node at a particular
 level.
    switch(e.Node.Depth)
    {
      case 0:
        // Populate the first-level nodes.
        PopulateCategories(e.Node);
        break;
      case 1:
        // Populate the second-level nodes.
        PopulateProducts(e.Node);
        break;
      default:
        // Do nothing.
        break;
    }
    
  }

  void PopulateCategories(TreeNode node)
  {
    
    // Query for the product categories. These are the values
    // for the second-level nodes.
    DataSet ResultSet = RunQuery("Select CategoryID, CategoryName From Categories");

    // Create the second-level nodes.
    if(ResultSet.Tables.Count > 0)
    {
    
      // Iterate through and create a new node for each row in the query
 results.
      // Notice that the query results are stored in the table of the
 DataSet.
      foreach (DataRow row in ResultSet.Tables[0].Rows)
      {
        
        // Create the new node. Notice that the CategoryId is stored
 in the Value property 
        // of the node. This will make querying for items in a specific
 category easier when
        // the third-level nodes are created. 
        TreeNode newNode = new TreeNode();
        newNode.Text = row["CategoryName"].ToString(); 
        newNode.Value = row["CategoryID"].ToString();        

        // Set the PopulateOnDemand property to true so that the child
 nodes can be 
        // dynamically populated.
        newNode.PopulateOnDemand = true;
        
        // Set additional properties for the node.
        newNode.SelectAction = TreeNodeSelectAction.Expand;
        
        // Add the new node to the ChildNodes collection of the parent
 node.
        node.ChildNodes.Add(newNode);
        
      }
      
    }
    
  }

  void PopulateProducts(TreeNode node)
  {

    // Query for the products of the current category. These are the
 values
    // for the third-level nodes.
    DataSet ResultSet = RunQuery("Select ProductName From Products Where CategoryID="
 + node.Value);

    // Create the third-level nodes.
    if(ResultSet.Tables.Count > 0)
    {
    
      // Iterate through and create a new node for each row in the query
 results.
      // Notice that the query results are stored in the table of the
 DataSet.
      foreach (DataRow row in ResultSet.Tables[0].Rows)
      {
      
        // Create the new node.
        TreeNode NewNode = new TreeNode(row["ProductName"].ToString());
        
        // Set the PopulateOnDemand property to false, because these
 are leaf nodes and
        // do not need to be populated.
        NewNode.PopulateOnDemand = false;
        
        // Set additional properties for the node.
        NewNode.SelectAction = TreeNodeSelectAction.None;
        
        // Add the new node to the ChildNodes collection of the parent
 node.
        node.ChildNodes.Add(NewNode);
        
      }
      
    }

  }

  DataSet RunQuery(String QueryString)
  {

    // Declare the connection string. This example uses Microsoft SQL
 Server 
    // and connects to the Northwind sample database.
    String ConnectionString = "server=localhost;database=NorthWind;Integrated
 Security=SSPI"; 

    SqlConnection DBConnection = new SqlConnection(ConnectionString);
    SqlDataAdapter DBAdapter;
    DataSet ResultsDataSet = new DataSet();

    try
    {

      // Run the query and create a DataSet.
      DBAdapter = new SqlDataAdapter(QueryString, DBConnection);
      DBAdapter.Fill(ResultsDataSet);

      // Close the database connection.
      DBConnection.Close();

    }
    catch(Exception ex)
    {

      // Close the database connection if it is still open.
      if(DBConnection.State == ConnectionState.Open)
      {
        DBConnection.Close();
      }
      
      Message.Text = "Unable to connect to the database.";

    }

    return ResultsDataSet;

  }

</script>

<html>
  <body>
    <form runat="server">
    
      <h3>TreeView PopulateNodesFromClient Example</h3>
    
      <asp:TreeView id="LinksTreeView"
        Font-Name= "Arial"
        ForeColor="Blue"
        EnableClientScript="true"
        PopulateNodesFromClient="true"  
        OnTreeNodePopulate="PopulateNode"
        runat="server">
         
        <Nodes>
        
          <asp:TreeNode Text="Inventory" 
            SelectAction="Expand"  
            PopulateOnDemand="true"/>
        
        </Nodes>
        
      </asp:TreeView>
      
      <br><br>
      
      <asp:Label id="Message" runat="server"/>

    </form>
  </body>
</html>

.NET Framework のセキュリティ.NET Frameworkセキュリティ
継承階層継承階層
System.Object
   System.Web.UI.Control
     System.Web.UI.WebControls.WebControl
       System.Web.UI.WebControls.BaseDataBoundControl
         System.Web.UI.WebControls.HierarchicalDataBoundControl
          System.Web.UI.WebControls.TreeView
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
TreeView メンバ
System.Web.UI.WebControls 名前空間
DataBoundControl.DataSourceID プロパティ
DataBindings
EnableClientScript
IHierarchicalDataSource
Nodes
ShowCheckBoxes
TreeNode クラス
TreeNodeBinding クラス
TreeNodeStyle クラス
TreeNodeCollection クラス
SiteMapDataSource クラス
TreeNodeCheckChanged
SelectedNodeChanged
TreeNodeExpanded
TreeNodeCollapsed
TreeNodePopulate
TreeNodeDataBound
その他の技術情報
ASP.NET サイト マップ

TreeView クラス

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

名前空間: System.Windows.Forms
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文構文

<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
Public Class TreeView
    Inherits Control
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] 
public class TreeView : Control
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)] 
public ref class TreeView : public
 Control
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ 
public class TreeView extends Control
ComVisibleAttribute(true) 
ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) 
public class TreeView extends
 Control
解説解説

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

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

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

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

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

メモメモ

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

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

メモメモ

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

使用例使用例

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

' 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
// 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 上に作成済みであることも前提にしています。

' 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
// 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();
}
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.
   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();
}
// 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
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Windows.Forms.Control
        System.Windows.Forms.TreeView
           System.ComponentModel.Design.ObjectSelectorEditor.Selector
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「TreeView クラス」の関連用語











TreeView クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



TreeView クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS