TreeView クラス
アセンブリ: 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
TreeView コントロールは、目次やファイル ディレクトリなどの階層データをツリー構造で表示する場合に使用され、次の機能をサポートします。
-
コントロールのノードを XML データ、表形式データ、またはリレーショナル データにバインドできるようにするデータ バインディング。
-
SiteMapDataSource コントロールとの統合によるサイト ナビゲーション。
-
ツリーの作成、ノードの設定、プロパティの設定などを動的に行うための、TreeView オブジェクト モデルへのプログラムによるアクセス。
TreeView コントロールはノードで構成されます。ツリー内の各エントリはノードと呼ばれ、TreeNode オブジェクトで表されます。ノード型は次のように定義されます。
ノードは、親と子の両方に該当することがあります。ただし、1 つのノードがルート ノード、親ノード、および葉ノードを兼ねることはありません。ノードの表示と動作に関する一部のプロパティは、ノードがルート、親、葉のどのノードに該当するかによって決定されます。
通常のツリー構造にはルート ノードが 1 つしかありませんが、TreeView コントロールを使用すると、ツリー構造に複数のルート ノードを追加できます。この機能は、製品カテゴリ一覧のように 1 つのルート ノードを表示せずに項目一覧を表示する場合に便利です。
各ノードには、Text プロパティと Value プロパティがあります。ノードに関連付けられているポストバック イベントに渡されるデータなど、ノードに関する補足データを格納するために Value プロパティが使用されている間、Text プロパティの値は TreeView に表示されます。
ノードは選択モードまたはナビゲーション モードのいずれかになります。既定では、ノードは選択モードになっています。ノードをナビゲーション モードにするには、ノードの NavigateUrl プロパティを、空の文字列 ("") 以外の値に設定します。ノードを選択モードにするには、ノードの NavigateUrl プロパティを空の文字列 ("") に設定します。
TreeView コントロールの最も単純なデータ モデルは、静的データです。宣言構文を使用して静的データを表示するには、まず TreeView コントロールの開始タグと終了タグの間に <Nodes> の開始タグと終了タグを入れ子にします。次に、<Nodes> の開始タグと終了タグの間に <asp:TreeNode> 要素を入れ子にして、ツリー構造を作成します。各 <asp:TreeNode> 要素は、ツリー内のノードを表し、TreeNode オブジェクトに割り当てられます。<asp:TreeNode> 要素の属性を設定して、各ノードのプロパティを設定できます。子ノードを作成するには、親ノードの <asp:TreeNode> の開始タグと終了タグの間に追加の <asp:TreeNode> 要素を入れ子にします。
TreeView コントロールはデータにバインドすることもできます。TreeView コントロールを適切なデータ ソースの種類にバインドするには、次の 2 つのメソッドのいずれかを使用します。
-
TreeView コントロールは、XmlDataSource コントロール、SiteMapDataSource コントロールなど、IHierarchicalDataSource インターフェイスを実装する任意のデータ ソース コントロールを使用できます。データ ソース コントロールにバインドするには、TreeView コントロールの DataSourceID プロパティをデータ ソース コントロールの ID 値に設定します。TreeView コントロールは、指定されたデータ ソース コントロールに自動的にバインドされます。データにバインドするには、この方法をお勧めします。
-
TreeView コントロールは、関連を持つ XmlDocument オブジェクトまたは DataSet オブジェクトにバインドすることもできます。このデータ ソースの 1 つにバインドするには、TreeView コントロールの DataSource プロパティをデータ ソースに設定してから、DataBind メソッドを呼び出します。
複数の属性を持つ XML 要素などのように、各データ項目に複数のプロパティが含まれているデータ ソースにバインドする場合、ノードにはデータ項目の ToString メソッドから返される値が既定で表示されます。XML 要素の場合、ノードには要素名が表示されます。これはメニュー ツリーの基になる構造体を示す以外はあまり用途はありません。DataBindings コレクションを使用してツリー ノードのバインディングを指定することにより、ノードを特定のデータ項目のプロパティにバインドできます。DataBindings コレクションには、データ項目とそのバインド先のノードとの間の関係を定義する TreeNodeBinding オブジェクトが含まれています。バインディングの基準、およびノードに表示するデータ項目のプロパティを指定できます。ツリー ノードのバインディングの詳細については、TreeNodeBinding のトピックを参照してください。
メモ |
---|
LevelStyles コレクションを使用して特定の深さレベルに対してスタイルが定義されている場合、そのスタイルは、その深さにあるノードのすべてのルート、親ノード、または葉ノードのスタイル設定をオーバーライドします。 |
別の方法でコントロールの外観を変更するには、TreeView コントロールに表示されるイメージをカスタマイズします。次の表に示されているプロパティを設定して、コントロールの部分ごとにの独自の一連のカスタム イメージを指定できます。
CollapseImageUrl | |
ExpandImageUrl | |
LineImagesFolder | 親ノードを子ノードに接続するために使用される線のイメージを格納するフォルダの URL。このプロパティを有効にするには、ShowLines プロパティを true に設定する必要もあります。 |
NoExpandImageUrl |
TreeView コントロールを使用すると、ノードの隣にチェック ボックスを表示することもできます。ShowCheckBoxes プロパティを TreeNodeTypes.None 以外の値に設定すると、指定したノード型の隣にチェック ボックスが表示されます。
ページをサーバーにポストするたびに、CheckedNodes コレクションには選択したノードが自動的に設定されます。チェック ボックスが表示されている場合、TreeNodeCheckChanged イベントを使用して、サーバーへの各ポストの間にチェック ボックスの状態が変更されるたびにカスタム ルーチンを実行できます。
イベント
TreeView コントロールには、プログラムに利用できる複数のイベントが用意されています。これにより、イベントが発生するたびにカスタム ルーチンが実行されるようにできます。TreeView コントロールでサポートされるイベントの一覧を次の表に示します。
ユーザー補助
このコントロールに既定でレンダリングされるマークアップは、Web Content Accessibility Guidelines (WCAG) 1.0 の優先度 1 ガイドラインなどのユーザー補助に関する標準に適合しない可能性があります。このコントロールのユーザー補助サポートの詳細については、「ASP.NET コントロールとユーザー補助」を参照してください。
TreeView コントロールにはスクロールが組み込まれていません。スクロールを追加するには、TreeView コントロールを Panel コントロールに配置し、スクロール バーを Panel コントロールに追加します。詳細については、「Panel Web サーバー コントロールの概要」を参照してください。
Topic | Location |
---|---|
チュートリアル : 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 アプリケーションの作成 |
次のコード例に対してフレームを設定する方法を次のコード例に示します。
<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>
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.BaseDataBoundControl
System.Web.UI.WebControls.HierarchicalDataBoundControl
System.Web.UI.WebControls.TreeView
プラットフォーム
Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
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 クラス
アセンブリ: 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
Nodes コレクションには、TreeView コントロールに割り当てられているすべての TreeNode オブジェクトが格納されます。このコレクション内のツリー ノードは、ルート ツリー ノードと呼ばれます。続けてルート ツリー ノードに追加されたツリー ノードは、子ノードと呼ばれます。各 TreeNode には、他の TreeNode オブジェクトのコレクションを含めることができるため、コレクションを反復処理するときにツリー構造内の位置がわからなくなる場合があります。TreeNode.FullPath 文字列を解析するときに PathSeparator 文字列値を使用すると、1 つの TreeNode ラベルがどこから始まってどこで終わっているかがわかります。
ツリー ノードの横にイメージを表示するには、ImageList を ImageList プロパティに割り当て、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 メソッドを呼び出して、ノードが展開された状態と折りたたまれた状態を切り替えることもできます。
ツリー ノードには、オプションでチェック ボックスを表示できます。チェック ボックスを表示するには、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 イベントを処理します。
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 は再描画されません。TreeView が TreeNode オブジェクトを作成して描画する間、待機 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.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.TreeView
System.ComponentModel.Design.ObjectSelectorEditor.Selector
プラットフォーム
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
- TreeView クラスのページへのリンク