.NET Framework Class Library HierarchicalDataBoundControl Class Serves as the base class for all ASP.NET version 2.0 data-bound controls that display their data in hierarchical form.

Inheritance Hierarchy
Namespace:
System.Web.UI.WebControls
Assembly:
System.Web (in System.Web.dll)

Syntax
Public MustInherit Class HierarchicalDataBoundControl _
Inherits BaseDataBoundControl
public abstract class HierarchicalDataBoundControl : BaseDataBoundControl
public ref class HierarchicalDataBoundControl abstract : public BaseDataBoundControl
[<AbstractClass>]
type HierarchicalDataBoundControl =
class
inherit BaseDataBoundControl
end
<asp:HierarchicalDataBoundControl />
The HierarchicalDataBoundControl type exposes the following members.

Constructors

Methods
|
| Name | Description |
|---|
.gif) | AddAttributesToRender | Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | AddedControl | Called after a child control is added to the Controls collection of the Control object. (Inherited from Control.) | .gif) | AddParsedSubObject | Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object. (Inherited from Control.) | .gif) | ApplyStyle | Copies any nonblank elements of the specified style to the Web control, overwriting any existing style elements of the control. This method is primarily used by control developers. (Inherited from WebControl.) | .gif) | ApplyStyleSheetSkin | Applies the style properties defined in the page style sheet to the control. (Inherited from Control.) | .gif) | BuildProfileTree | Infrastructure. Gathers information about the server control and delivers it to the Trace property to be displayed when tracing is enabled for the page. (Inherited from Control.) | .gif) | ClearCachedClientID | Infrastructure. Sets the cached ClientID value to nullNothingnullptra null reference (Nothing in Visual Basic). (Inherited from Control.) | .gif) | ClearChildControlState | Deletes the control-state information for the server control's child controls. (Inherited from Control.) | .gif) | ClearChildState | Deletes the view-state and control-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearChildViewState | Deletes the view-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Sets the ClientIDMode property of the current control instance and of any child controls to Inherit. (Inherited from Control.) | .gif) | ConfirmInitState | Sets the initialized state of the data-bound control. (Inherited from BaseDataBoundControl.) | .gif) | CopyBaseAttributes | Copies the properties not encapsulated by the Style object from the specified Web server control to the Web server control that this method is called from. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | CreateChildControls | Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. (Inherited from Control.) | .gif) | CreateControlCollection | Creates a new ControlCollection object to hold the child controls (both literal and server) of the server control. (Inherited from Control.) | .gif) | CreateControlStyle | Creates the style object that is used internally by the WebControl class to implement all style related properties. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | DataBind()()() | Binds a data source to the invoked server control and all its child controls. (Inherited from BaseDataBoundControl.) | .gif) | DataBind(Boolean) | Binds a data source to the invoked server control and all its child controls with an option to raise the DataBinding event. (Inherited from Control.) | .gif) | DataBindChildren | Binds a data source to the server control's child controls. (Inherited from Control.) | .gif) | Dispose | Enables a server control to perform final clean up before it is released from memory. (Inherited from Control.) | .gif) | EnsureChildControls | Determines whether the server control contains child controls. If it does not, it creates child controls. (Inherited from Control.) | .gif) | EnsureDataBound | Calls the DataBind method if the DataSourceID property is set and the data-bound control is marked to require binding. (Inherited from BaseDataBoundControl.) | .gif) | EnsureID | Creates an identifier for controls that do not have an identifier assigned. (Inherited from Control.) | .gif) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) | FindControl(String) | Searches the current naming container for a server control with the specified id parameter. (Inherited from Control.) | .gif) | FindControl(String, Int32) | Infrastructure. Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search. You should not override this version of the FindControl method. (Inherited from Control.) | .gif) | Focus | Sets input focus to a control. (Inherited from Control.) | .gif) | GetData | Retrieves a HierarchicalDataSourceView object that the data-bound control uses to perform data operations. | .gif) | GetDataSource | Retrieves the IHierarchicalDataSource that the data-bound control is associated with, if any. | .gif) | GetDesignModeState | Infrastructure. Gets design-time data for a control. (Inherited from Control.) | .gif) | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | .gif) | GetRouteUrl(Object) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(String, Object) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) | GetUniqueIDRelativeTo | Returns the prefixed portion of the UniqueID property of the specified control. (Inherited from Control.) | .gif) | HasControls | Determines if the server control contains any child controls. (Inherited from Control.) | .gif) | HasEvents | Returns a value indicating whether events are registered for the control or any child controls. (Inherited from Control.) | .gif) | IsLiteralContent | Infrastructure. Determines if the server control holds only literal content. (Inherited from Control.) | .gif) | LoadControlState | Restores control-state information from a previous page request that was saved by the SaveControlState method. (Inherited from Control.) | .gif) | LoadViewState | Restores view-state information from a previous request that was saved with the SaveViewState method. (Inherited from WebControl.) | .gif) | MapPathSecure | Retrieves the physical path that a virtual path, either absolute or relative, maps to. (Inherited from Control.) | .gif) | MarkAsDataBound | Sets the state of the control in view state as successfully bound to data. | .gif) | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) | MergeStyle | Copies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | OnBubbleEvent | Determines whether the event for the server control is passed up the page's UI server control hierarchy. (Inherited from Control.) | .gif) | OnDataBinding | Raises the DataBinding event. (Inherited from Control.) | .gif) | OnDataBound | Raises the DataBound event. (Inherited from BaseDataBoundControl.) | .gif) | OnDataPropertyChanged | Called when one of the base data source identification properties is changed, to re-bind the data-bound control to its data. (Overrides BaseDataBoundControl..::.OnDataPropertyChanged()()().) | .gif) | OnDataSourceChanged | Called when the IHierarchicalDataSource instance that the data-bound control works with raises the DataSourceChanged event. | .gif) | OnInit | Handles the Init event. (Inherited from BaseDataBoundControl.) | .gif) | OnLoad | Handles the Load event. (Overrides Control..::.OnLoad(EventArgs).) | .gif) | OnPagePreLoad | Sets the initialized state of the data-bound control before the control is loaded. (Overrides BaseDataBoundControl..::.OnPagePreLoad(Object, EventArgs).) | .gif) | OnPreRender | Handles the PreRender event. (Inherited from BaseDataBoundControl.) | .gif) | OnUnload | Raises the Unload event. (Inherited from Control.) | .gif) | OpenFile | Gets a Stream used to read a file. (Inherited from Control.) | .gif) | PerformDataBinding | When overridden in a derived class, binds data from the data source to the control. | .gif) | PerformSelect | Retrieves data from the associated data source. (Overrides BaseDataBoundControl..::.PerformSelect()()().) | .gif) | RaiseBubbleEvent | Assigns any sources of the event and its information to the control's parent. (Inherited from Control.) | .gif) | RemovedControl | Called after a child control is removed from the Controls collection of the Control object. (Inherited from Control.) | .gif) | Render | Renders the control to the specified HTML writer. (Inherited from WebControl.) | .gif) | RenderBeginTag | Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | RenderChildren | Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client. (Inherited from Control.) | .gif) | RenderContents | Renders the contents of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | RenderControl(HtmlTextWriter) | Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled. (Inherited from Control.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object. (Inherited from Control.) | .gif) | RenderEndTag | Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | ResolveAdapter | Gets the control adapter responsible for rendering the specified control. (Inherited from Control.) | .gif) | ResolveClientUrl | Gets a URL that can be used by the browser. (Inherited from Control.) | .gif) | ResolveUrl | Converts a URL into one that is usable on the requesting client. (Inherited from Control.) | .gif) | SaveControlState | Saves any server control state changes that have occurred since the time the page was posted back to the server. (Inherited from Control.) | .gif) | SaveViewState | Saves any state that was modified after the TrackViewState method was invoked. (Inherited from WebControl.) | .gif) | SetDesignModeState | Sets design-time data for a control. (Inherited from Control.) | .gif) | SetRenderMethodDelegate | Infrastructure. Assigns an event handler delegate to render the server control and its content into its parent control. (Inherited from Control.) | .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | .gif) | TrackViewState | Causes the control to track changes to its view state so they can be stored in the object's ViewState property. (Inherited from WebControl.) | .gif) | ValidateDataSource | Verifies that the object a data-bound control binds to is one it can work with. (Overrides BaseDataBoundControl..::.ValidateDataSource(Object).) | Top

Extension Methods

Explicit Interface Implementations
|
| Name | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Gets an attribute of the Web control with the specified name. (Inherited from WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Sets an attribute of the Web control to the specified name and value. (Inherited from WebControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | For a description of this member, see IControlBuilderAccessor..::.ControlBuilder. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.GetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.SetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. For a description of this member, see IControlDesignerAccessor..::.SetOwnerControl. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | For a description of this member, see IControlDesignerAccessor..::.UserData. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | For a description of this member, see IDataBindingsAccessor..::.DataBindings. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | For a description of this member, see IDataBindingsAccessor..::.HasDataBindings. (Inherited from Control.) | .gif) .gif) | IExpressionsAccessor..::.Expressions | For a description of this member, see IExpressionsAccessor..::.Expressions. (Inherited from Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | For a description of this member, see IExpressionsAccessor..::.HasExpressions. (Inherited from Control.) | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | For a description of this member, see IParserAccessor..::.AddParsedSubObject. (Inherited from Control.) | Top

Remarks
The HierarchicalDataBoundControl class is the base class used for ASP.NET controls that retrieve data from an ASP.NET hierarchical data source control and bind user-interface elements of the control to that data for display. The TreeView and Menu classes derive from HierarchicalDataBoundControl. Page developers do not use the HierarchicalDataBoundControl class directly; instead, they use controls that derive from this class. Controls developers extend this class to create data-bound controls that work with classes that implement the IHierarchicalDataSource interface and classes that derive from the HierarchicalDataSourceControl and HierarchicalDataSourceView classes. When deriving a class from the HierarchicalDataBoundControl class, override the PerformDataBinding method to bind the user-interface elements of your control to data retrieved by the GetData method. In most cases, the PerformDataBinding method is the only method you will override in your derived class. For ASP.NET 2.0 data-bound controls, the PerformSelect method is the equivalent of the DataBind method, and is called to bind data at run time. The PerformSelect method calls the GetData and PerformDataBinding methods.

Examples
The following code example demonstrates how to derive a class from the HierarchicalDataBoundControl class to create a custom data-bound control. The GeneologyTree control renders a pre HTML section with a text tree for the data retrieved from an associated data source control.
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB.Controls
<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class GeneologyTree
Inherits HierarchicalDataBoundControl
Dim MaxDepth As Integer = 0
Private aRootNode As TreeNode
Public ReadOnly Property RootNode() As TreeNode
Get
If aRootNode Is Nothing Then
aRootNode = New TreeNode(String.Empty)
End If
Return aRootNode
End Get
End Property
Private alNodes As ArrayList
Public ReadOnly Property Nodes() As ArrayList
Get
If alNodes Is Nothing Then
alNodes = New ArrayList()
End If
Return alNodes
End Get
End Property
Public Property DataTextField() As String
Get
Dim o As Object = ViewState("DataTextField")
If o Is Nothing Then
Return String.Empty
Else
Return CStr(o)
End If
End Get
Set(ByVal value As String)
ViewState("DataTextField") = value
If Initialized Then
OnDataPropertyChanged()
End If
End Set
End Property
Protected Overrides Sub PerformDataBinding()
MyBase.PerformDataBinding()
' Do not attempt to bind data if there is no
' data source set.
If Not IsBoundUsingDataSourceID AndAlso DataSource Is Nothing Then
Return
End If
Dim view As HierarchicalDataSourceView = GetData(RootNode.DataPath)
If view Is Nothing Then
Throw New InvalidOperationException _
("No view returned by data source control.")
End If
Dim enumerable As IHierarchicalEnumerable = view.Select()
If Not (enumerable Is Nothing) Then
Nodes.Clear()
Try
RecurseDataBindInternal(RootNode, enumerable, 1)
Finally
End Try
End If
End Sub ' PerformDataBinding
Private Sub RecurseDataBindInternal(ByVal node As TreeNode, _
ByVal enumerable As IHierarchicalEnumerable, _
ByVal depth As Integer)
Dim item As Object
For Each item In enumerable
Dim data As IHierarchyData = enumerable.GetHierarchyData(item)
If Not data Is Nothing Then
' Create an object that represents the bound data
' to the control.
Dim newNode As New TreeNode()
Dim rvnode As New RootViewNode()
rvnode.Node = newNode
rvnode.Depth = depth
' The dataItem is not just a string, but potentially
' an XML node or some other container.
' If DataTextField is set, use it to determine which
' field to render. Otherwise, use the first field.
If DataTextField.Length > 0 Then
newNode.Text = DataBinder.GetPropertyValue _
(data, DataTextField, Nothing)
Else
Dim props As PropertyDescriptorCollection = _
TypeDescriptor.GetProperties(data)
' Set the "default" value of the node.
newNode.Text = String.Empty
' Set the true data-bound value of the TextBox,
' if possible.
If props.Count >= 1 Then
If Not props(0).GetValue(data) Is Nothing Then
newNode.Text = props(0).GetValue(data).ToString()
End If
End If
End If
Nodes.Add(rvnode)
If data.HasChildren Then
Dim newEnumerable As IHierarchicalEnumerable = _
data.GetChildren()
If Not (newEnumerable Is Nothing) Then
RecurseDataBindInternal(newNode, _
newEnumerable, depth + 1)
End If
End If
If MaxDepth < depth Then
MaxDepth = depth
End If
End If
Next item
End Sub 'RecurseDataBindInternal
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
writer.WriteLine("<PRE>")
Dim currentDepth As Integer = 1
Dim currentTextLen As Integer = 0
Dim rvnode As RootViewNode
For Each rvnode In Nodes
If rvnode.Depth = currentDepth Then
Dim output As String = " " + rvnode.Node.Text + " "
writer.Write(output)
currentTextLen = currentTextLen + output.Length
Else
writer.WriteLine("")
' Some very basic whitespace formatting.
' The implicit conversion to an Integer is fine, as
' a general estimate is acceptable for this
' simple example.
Dim halfLine As Integer = CInt(currentTextLen / 2)
Dim i As Integer
For i = 0 To halfLine
writer.Write(" "c)
Next i
writer.Write("|"c)
writer.WriteLine("")
currentDepth += 1
Dim j As Integer
For j = 0 To halfLine
writer.Write(" "c)
Next j
Dim output As String = " " + rvnode.Node.Text + " "
writer.Write(output)
currentTextLen = currentTextLen + output.Length
End If
Next rvnode
writer.WriteLine("</PRE>")
End Sub 'Render
Private Class RootViewNode
Public Node As TreeNode
Public Depth As Integer
End Class 'RootViewNode
End Class 'GeneologyTree
End Namespace
using System;
using System.Collections;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Samples.AspNet.CS.Controls {
[AspNetHostingPermission(SecurityAction.Demand,
Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level=AspNetHostingPermissionLevel.Minimal)]
public class GeneologyTree : HierarchicalDataBoundControl {
private TreeNode rootNode;
public TreeNode RootNode {
get {
if (rootNode == null) {
rootNode = new TreeNode(String.Empty);
}
return rootNode;
}
}
private ArrayList nodes;
public ArrayList Nodes {
get {
if (null == nodes) {
nodes = new ArrayList();
}
return nodes;
}
}
public string DataTextField {
get {
object o = ViewState["DataTextField"];
return((o == null) ? string.Empty : (string)o);
}
set {
ViewState["DataTextField"] = value;
if (Initialized) {
OnDataPropertyChanged();
}
}
}
private int _maxDepth = 0;
protected override void PerformDataBinding() {
base.PerformDataBinding();
// Do not attempt to bind data if there is no
// data source set.
if (!IsBoundUsingDataSourceID && (DataSource == null)) {
return;
}
HierarchicalDataSourceView view = GetData(RootNode.DataPath);
if (view == null) {
throw new InvalidOperationException
("No view returned by data source control.");
}
IHierarchicalEnumerable enumerable = view.Select();
if (enumerable != null) {
Nodes.Clear();
try {
RecurseDataBindInternal(RootNode, enumerable, 1);
}
finally {
}
}
}
private void RecurseDataBindInternal(TreeNode node,
IHierarchicalEnumerable enumerable, int depth) {
foreach(object item in enumerable) {
IHierarchyData data = enumerable.GetHierarchyData(item);
if (null != data) {
// Create an object that represents the bound data
// to the control.
TreeNode newNode = new TreeNode();
RootViewNode rvnode = new RootViewNode();
rvnode.Node = newNode;
rvnode.Depth = depth;
// The dataItem is not just a string, but potentially
// an XML node or some other container.
// If DataTextField is set, use it to determine which
// field to render. Otherwise, use the first field.
if (DataTextField.Length > 0) {
newNode.Text = DataBinder.GetPropertyValue
(data, DataTextField, null);
}
else {
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(data);
// Set the "default" value of the node.
newNode.Text = String.Empty;
// Set the true data-bound value of the TextBox,
// if possible.
if (props.Count >= 1) {
if (null != props[0].GetValue(data)) {
newNode.Text =
props[0].GetValue(data).ToString();
}
}
}
Nodes.Add(rvnode);
if (data.HasChildren) {
IHierarchicalEnumerable newEnumerable =
data.GetChildren();
if (newEnumerable != null) {
RecurseDataBindInternal(newNode,
newEnumerable, depth+1 );
}
}
if ( _maxDepth < depth) _maxDepth = depth;
}
}
}
protected override void Render(HtmlTextWriter writer) {
writer.WriteLine("<PRE>");
int currentDepth = 1;
int currentTextLen = 0;
foreach (RootViewNode rvnode in Nodes) {
if (rvnode.Depth == currentDepth) {
string output = " " + rvnode.Node.Text + " ";
writer.Write(output);
currentTextLen = currentTextLen + output.Length;
}
else {
writer.WriteLine("");
// Some very basic whitespace formatting
int halfLine = currentTextLen / 2;
for (int i=0;i<halfLine;i++) {
writer.Write(' ');
}
writer.Write('|');
writer.WriteLine("");
++currentDepth;
currentTextLen = 0;
for (int j=0;j<halfLine;j++) {
writer.Write(' ');
}
string output = " " + rvnode.Node.Text + " ";
writer.Write(output);
currentTextLen = currentTextLen + output.Length;
}
}
writer.WriteLine("</PRE>");
}
private class RootViewNode {
public TreeNode Node;
public int Depth;
}
}
}
The following code example demonstrates how to use the GeneologyTree control, defined in the previous example, and bind it to an XmlDataSource control.
<%@Page language="VB" %>
<%@ Register TagPrefix="aspSample"
Namespace="Samples.AspNet.VB.Controls"
Assembly="Samples.AspNet.VB.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>VB Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<aspSample:geneologytree
id="GeneologyTree1"
runat="server"
datatextfield="title"
datasourceid="XmlDataSource1" />
<asp:xmldatasource
id="XmlDataSource1"
datafile="geneology.xml"
runat="server" />
</form>
</body>
</html>
<%@Page language="c#" %>
<%@ Register TagPrefix="aspSample"
Namespace="Samples.AspNet.CS.Controls"
Assembly="Samples.AspNet.CS.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<aspSample:geneologytree
id="GeneologyTree1"
runat="server"
datatextfield="title"
datasourceid="XmlDataSource1" />
<asp:xmldatasource
id="XmlDataSource1"
datafile="geneology.xml"
runat="server" />
</form>
</body>
</html>
The geneology.xml file accessed in the code example contains the following data.
<family>
<member title="great-grandfather">
<member title="grandfather" >
<member title="child" />
<member title="father" >
<member title="son" />
</member>
</member>
</member>
</family>

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Bibliothèque de classes .NET Framework HierarchicalDataBoundControl, classe Sert de classe de base pour tous les contrôles liés aux données ASP.NET version 2.0 qui affichent leurs données de manière hiérarchique.

Hiérarchie d'héritage
Espace de noms :
System.Web.UI.WebControls
Assembly :
System.Web (dans System.Web.dll)

Syntaxe
Public MustInherit Class HierarchicalDataBoundControl _
Inherits BaseDataBoundControl
public abstract class HierarchicalDataBoundControl : BaseDataBoundControl
public ref class HierarchicalDataBoundControl abstract : public BaseDataBoundControl
[<AbstractClass>]
type HierarchicalDataBoundControl =
class
inherit BaseDataBoundControl
end
<asp:HierarchicalDataBoundControl />
Le type HierarchicalDataBoundControl expose les membres suivants.

Constructeurs

Méthodes
|
| Nom | Description |
|---|
.gif) | AddAttributesToRender | Ajoute des attributs et des styles HTML qui doivent être rendus au HtmlTextWriterTag spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | AddedControl | Appelée après l'ajout d'un contrôle enfant à la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | AddParsedSubObject | Avertit le contrôle serveur qu'un élément XML ou HTML a été analysé et l'ajoute à l'objet ControlCollection du contrôle serveur. (Hérité de Control.) | .gif) | ApplyStyle | Copie tous les éléments non vides du style spécifié vers le contrôle Web, en remplaçant les éléments de style existants du contrôle. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | ApplyStyleSheetSkin | Applique les propriétés de style définies dans la feuille de style de la page au contrôle. (Hérité de Control.) | .gif) | BuildProfileTree | Infrastructure. Collecte des informations sur le contrôle serveur et les livre à la propriété Trace à afficher lorsque le traçage est activé pour la page. (Hérité de Control.) | .gif) | ClearCachedClientID | Infrastructure. Affecte à la valeur ClientID mise en cache la valeur nullNothingnullptrune référence null (Nothing en Visual Basic). (Hérité de Control.) | .gif) | ClearChildControlState | Supprime les informations sur l'état du contrôle des contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildState | Supprime les informations sur l'état d'affichage et sur l'état du contrôle de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildViewState | Supprime les informations d'état d'affichage de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Affecte la valeur Inherit à la propriété ClientIDMode de l'instance de contrôle actuelle et de tous contrôles enfants. (Hérité de Control.) | .gif) | ConfirmInitState | Définit l'état initialisé du contrôle lié aux données. (Hérité de BaseDataBoundControl.) | .gif) | CopyBaseAttributes | Copie les propriétés non encapsulées par l'objet Style du contrôle serveur Web spécifié vers le contrôle serveur Web à partir duquel cette méthode est appelée. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | CreateChildControls | Appelé par l'infrastructure de page ASP.NET pour avertir les contrôles serveur qui utilisent une implémentation basée sur la composition qu'ils doivent créer tous les contrôles enfants qu'ils contiennent en préparation de la publication ou du rendu. (Hérité de Control.) | .gif) | CreateControlCollection | Crée un nouvel objet ControlCollection pour contenir les contrôles enfants (littéraux et serveur) du contrôle serveur. (Hérité de Control.) | .gif) | CreateControlStyle | Crée l'objet de style qui est utilisé de manière interne par la classe WebControl pour implémenter toutes les propriétés associées au style. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | DataBind()()() | Lie une source de données au contrôle serveur appelé et à tous ses contrôles enfants. (Hérité de BaseDataBoundControl.) | .gif) | DataBind(Boolean) | Lie une source de données au contrôle serveur appelé et tous ses contrôles enfants avec une option pour déclencher l'événement DataBinding. (Hérité de Control.) | .gif) | DataBindChildren | Lie une source de données aux contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | Dispose | Permet à un contrôle serveur d'effectuer le nettoyage final avant qu'il soit libéré de la mémoire. (Hérité de Control.) | .gif) | EnsureChildControls | Détermine si le contrôle serveur contient des contrôles enfants. S'il ne contient pas de contrôles enfants, il en crée. (Hérité de Control.) | .gif) | EnsureDataBound | Appelle la méthode DataBind si la propriété DataSourceID est définie et que le contrôle lié aux données est marqué pour demander à être lié. (Hérité de BaseDataBoundControl.) | .gif) | EnsureID | Crée un identificateur pour les contrôles auxquels aucun identificateur n'est assigné. (Hérité de Control.) | .gif) | Equals(Object) | Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.) | .gif) | Finalize | Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.) | .gif) | FindControl(String) | Recherche un contrôle serveur possédant le paramètre id spécifié dans le conteneur d'attribution de noms actuel. (Hérité de Control.) | .gif) | FindControl(String, Int32) | Infrastructure. Recherche le conteneur d'attribution de noms actuel d'un contrôle serveur avec l'id spécifié et un entier, spécifié dans le paramètre pathOffset, qui facilite la recherche. Vous ne devez pas substituer cette version de la méthode FindControl. (Hérité de Control.) | .gif) | Focus | Affecte le focus d'entrée à un contrôle. (Hérité de Control.) | .gif) | GetData | Récupère un objet HierarchicalDataSourceView que le contrôle lié aux données utilise pour exécuter des opérations de données. | .gif) | GetDataSource | Récupère le IHierarchicalDataSource auquel le contrôle lié aux données est associé, le cas échéant. | .gif) | GetDesignModeState | Infrastructure. Obtient les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | GetHashCode | Sert de fonction de hachage pour un type particulier. (Hérité de Object.) | .gif) | GetRouteUrl(Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetType | Obtient le Type de l'instance actuelle. (Hérité de Object.) | .gif) | GetUniqueIDRelativeTo | Retourne la partie préfixée de la propriété UniqueID du contrôle spécifié. (Hérité de Control.) | .gif) | HasControls | Détermine si le contrôle serveur contient des contrôles enfants. (Hérité de Control.) | .gif) | HasEvents | Retourne une valeur indiquant si des événements sont inscrits pour le contrôle ou des contrôles enfants. (Hérité de Control.) | .gif) | IsLiteralContent | Infrastructure. Détermine si le contrôle serveur ne détient qu'un contenu littéral. (Hérité de Control.) | .gif) | LoadControlState | Restaure des informations sur l'état du contrôle à partir d'une demande de page antérieure enregistrée par la méthode SaveControlState. (Hérité de Control.) | .gif) | LoadViewState | Restaure les informations d'état d'affichage à partir d'une précédente requête enregistrées avec la méthode SaveViewState. (Hérité de WebControl.) | .gif) | MapPathSecure | Récupère le chemin d'accès physique auquel un chemin d'accès virtuel, absolu ou relatif, correspond. (Hérité de Control.) | .gif) | MarkAsDataBound | Définit l'état du contrôle dans l'état d'affichage comme lié avec succès aux données. | .gif) | MemberwiseClone | Crée une copie superficielle de l'objet Object actif. (Hérité de Object.) | .gif) | MergeStyle | Copie tous les éléments non vides du style spécifié vers le contrôle Web, mais ne remplace aucun élément de style existant du contrôle. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | OnBubbleEvent | Détermine si l'événement pour le contrôle serveur est passé dans la hiérarchie des contrôles serveur de l'interface utilisateur de la page. (Hérité de Control.) | .gif) | OnDataBinding | Déclenche l'événement DataBinding. (Hérité de Control.) | .gif) | OnDataBound | Déclenche l'événement DataBound. (Hérité de BaseDataBoundControl.) | .gif) | OnDataPropertyChanged | Appelé lorsque l'une des propriétés d'identification de la source de données de base est modifiée, pour rétablir la liaison du contrôle lié aux données à ses données. (Substitue BaseDataBoundControl..::.OnDataPropertyChanged()()().) | .gif) | OnDataSourceChanged | Appelé lorsque l'instance de IHierarchicalDataSource avec laquelle fonctionne le contrôle lié aux données déclenche l'événement DataSourceChanged. | .gif) | OnInit | Gère l'événement Init. (Hérité de BaseDataBoundControl.) | .gif) | OnLoad | Gère l'événement Load. (Substitue Control..::.OnLoad(EventArgs).) | .gif) | OnPagePreLoad | Définit l'état initialisé du contrôle lié aux données avant que le contrôle ne soit chargé. (Substitue BaseDataBoundControl..::.OnPagePreLoad(Object, EventArgs).) | .gif) | OnPreRender | Gère l'événement PreRender. (Hérité de BaseDataBoundControl.) | .gif) | OnUnload | Déclenche l'événement Unload. (Hérité de Control.) | .gif) | OpenFile | Obtient un Stream utilisé pour lire un fichier. (Hérité de Control.) | .gif) | PerformDataBinding | En cas de substitution dans une classe dérivée, lie des données de la source de données au contrôle. | .gif) | PerformSelect | Récupère les données de la source de données associée. (Substitue BaseDataBoundControl..::.PerformSelect()()().) | .gif) | RaiseBubbleEvent | Assigne les sources éventuelles de l'événement et ses informations au parent du contrôle. (Hérité de Control.) | .gif) | RemovedControl | Appelée après la suppression d'un contrôle enfant dans la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | Render | Génère le rendu du contrôle via le writer HTML spécifié. (Hérité de WebControl.) | .gif) | RenderBeginTag | Génère le rendu de la balise d'ouverture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderChildren | Renvoie le contenu des enfants d'un contrôle serveur dans un objet HtmlTextWriter fourni, qui écrit le contenu à rendre sur le client. (Hérité de Control.) | .gif) | RenderContents | Génère le rendu du contenu du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderControl(HtmlTextWriter) | Renvoie le contenu du contrôle serveur dans un objet HtmlTextWriter fourni et stocke des informations de traçage au sujet du contrôle si le traçage est activé. (Hérité de Control.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Génère le contenu du contrôle serveur dans un objet HtmlTextWriter à l'aide d'un objet ControlAdapter fourni. (Hérité de Control.) | .gif) | RenderEndTag | Génère le rendu de la balise de fermeture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | ResolveAdapter | Obtient l'adaptateur de contrôles responsable du rendu du contrôle spécifié. (Hérité de Control.) | .gif) | ResolveClientUrl | Obtient une URL qui peut être utilisée par le navigateur. (Hérité de Control.) | .gif) | ResolveUrl | Convertit une URL en une URL que le client soit en mesure d'utiliser. (Hérité de Control.) | .gif) | SaveControlState | Enregistre les modifications éventuellement apportées à l'état du contrôle serveur depuis la publication de la page sur le serveur. (Hérité de Control.) | .gif) | SaveViewState | Enregistre les états modifiés après l'appel de la méthode TrackViewState. (Hérité de WebControl.) | .gif) | SetDesignModeState | Définit les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | SetRenderMethodDelegate | Infrastructure. Assigne un délégué de gestionnaires d'événements pour générer le rendu du contrôle serveur et de son contenu dans son contrôle parent. (Hérité de Control.) | .gif) | ToString | Retourne une chaîne qui représente l'objet actuel. (Hérité de Object.) | .gif) | TrackViewState | Amène le contrôle à suivre les modifications apportées à son état d'affichage afin qu'elles puissent être stockées dans la propriété ViewState de l'objet. (Hérité de WebControl.) | .gif) | ValidateDataSource | Vérifie que l'objet auquel un contrôle lié aux données se lie est un objet avec qui il peut fonctionner. (Substitue BaseDataBoundControl..::.ValidateDataSource(Object).) | Début

Méthodes d'extension

Implémentations d'interface explicite
|
| Nom | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Obtient un attribut du contrôle Web avec le nom spécifié. (Hérité de WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Affecte au nom et à la valeur spécifiés un attribut du contrôle Web. (Hérité de WebControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | Pour obtenir une description de ce membre, consultez IControlBuilderAccessor..::.ControlBuilder. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.GetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetOwnerControl. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.UserData. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.DataBindings. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.HasDataBindings. (Hérité de Control.) | .gif) .gif) | IExpressionsAccessor..::.Expressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.Expressions. (Hérité de Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.HasExpressions. (Hérité de Control.) | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | Pour obtenir une description de ce membre, consultez IParserAccessor..::.AddParsedSubObject. (Hérité de Control.) | Début

Notes
La classe HierarchicalDataBoundControl est la classe de base utilisée pour les contrôles ASP.NET qui récupèrent des données d'un contrôle de source de données hiérarchique ASP.NET et lient les éléments de l'interface utilisateur du contrôle à ces données pour l'affichage. Les classes TreeView et Menu dérivent de HierarchicalDataBoundControl. Les développeurs de pages n'utilisent pas directement la classe HierarchicalDataBoundControl, mais des contrôles dérivés de cette classe. Les développeurs de contrôles étendent cette classe pour créer des contrôles liés aux données fonctionnant avec les classes qui implémentent l'interface IHierarchicalDataSource et les classes dérivées des classes HierarchicalDataSourceControl et HierarchicalDataSourceView. Lorsque vous dérivez une classe de la classe HierarchicalDataBoundControl, substituez la méthode PerformDataBinding pour lier les éléments de l'interface utilisateur de votre contrôle aux données récupérées par la méthode GetData. Dans la plupart des cas, PerformDataBinding est la seule méthode que vous substituerez dans votre classe dérivée. Pour les contrôles liés aux données ASP.NET 2.0, la méthode PerformSelect est l'équivalent de la méthode DataBind et est appelée pour lier les données au moment de l'exécution. La méthode PerformSelect appelle les méthodes GetData et PerformDataBinding.

Exemples
L'exemple de code suivant montre comment dériver une classe de la classe HierarchicalDataBoundControl pour créer un contrôle lié aux données personnalisé. Le contrôle GeneologyTree restitue une section HTML pre avec une arborescence de texte pour les données récupérées d'un contrôle de source de données associé.
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB.Controls
<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class GeneologyTree
Inherits HierarchicalDataBoundControl
Dim MaxDepth As Integer = 0
Private aRootNode As TreeNode
Public ReadOnly Property RootNode() As TreeNode
Get
If aRootNode Is Nothing Then
aRootNode = New TreeNode(String.Empty)
End If
Return aRootNode
End Get
End Property
Private alNodes As ArrayList
Public ReadOnly Property Nodes() As ArrayList
Get
If alNodes Is Nothing Then
alNodes = New ArrayList()
End If
Return alNodes
End Get
End Property
Public Property DataTextField() As String
Get
Dim o As Object = ViewState("DataTextField")
If o Is Nothing Then
Return String.Empty
Else
Return CStr(o)
End If
End Get
Set(ByVal value As String)
ViewState("DataTextField") = value
If Initialized Then
OnDataPropertyChanged()
End If
End Set
End Property
Protected Overrides Sub PerformDataBinding()
MyBase.PerformDataBinding()
' Do not attempt to bind data if there is no
' data source set.
If Not IsBoundUsingDataSourceID AndAlso DataSource Is Nothing Then
Return
End If
Dim view As HierarchicalDataSourceView = GetData(RootNode.DataPath)
If view Is Nothing Then
Throw New InvalidOperationException _
("No view returned by data source control.")
End If
Dim enumerable As IHierarchicalEnumerable = view.Select()
If Not (enumerable Is Nothing) Then
Nodes.Clear()
Try
RecurseDataBindInternal(RootNode, enumerable, 1)
Finally
End Try
End If
End Sub ' PerformDataBinding
Private Sub RecurseDataBindInternal(ByVal node As TreeNode, _
ByVal enumerable As IHierarchicalEnumerable, _
ByVal depth As Integer)
Dim item As Object
For Each item In enumerable
Dim data As IHierarchyData = enumerable.GetHierarchyData(item)
If Not data Is Nothing Then
' Create an object that represents the bound data
' to the control.
Dim newNode As New TreeNode()
Dim rvnode As New RootViewNode()
rvnode.Node = newNode
rvnode.Depth = depth
' The dataItem is not just a string, but potentially
' an XML node or some other container.
' If DataTextField is set, use it to determine which
' field to render. Otherwise, use the first field.
If DataTextField.Length > 0 Then
newNode.Text = DataBinder.GetPropertyValue _
(data, DataTextField, Nothing)
Else
Dim props As PropertyDescriptorCollection = _
TypeDescriptor.GetProperties(data)
' Set the "default" value of the node.
newNode.Text = String.Empty
' Set the true data-bound value of the TextBox,
' if possible.
If props.Count >= 1 Then
If Not props(0).GetValue(data) Is Nothing Then
newNode.Text = props(0).GetValue(data).ToString()
End If
End If
End If
Nodes.Add(rvnode)
If data.HasChildren Then
Dim newEnumerable As IHierarchicalEnumerable = _
data.GetChildren()
If Not (newEnumerable Is Nothing) Then
RecurseDataBindInternal(newNode, _
newEnumerable, depth + 1)
End If
End If
If MaxDepth < depth Then
MaxDepth = depth
End If
End If
Next item
End Sub 'RecurseDataBindInternal
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
writer.WriteLine("<PRE>")
Dim currentDepth As Integer = 1
Dim currentTextLen As Integer = 0
Dim rvnode As RootViewNode
For Each rvnode In Nodes
If rvnode.Depth = currentDepth Then
Dim output As String = " " + rvnode.Node.Text + " "
writer.Write(output)
currentTextLen = currentTextLen + output.Length
Else
writer.WriteLine("")
' Some very basic whitespace formatting.
' The implicit conversion to an Integer is fine, as
' a general estimate is acceptable for this
' simple example.
Dim halfLine As Integer = CInt(currentTextLen / 2)
Dim i As Integer
For i = 0 To halfLine
writer.Write(" "c)
Next i
writer.Write("|"c)
writer.WriteLine("")
currentDepth += 1
Dim j As Integer
For j = 0 To halfLine
writer.Write(" "c)
Next j
Dim output As String = " " + rvnode.Node.Text + " "
writer.Write(output)
currentTextLen = currentTextLen + output.Length
End If
Next rvnode
writer.WriteLine("</PRE>")
End Sub 'Render
Private Class RootViewNode
Public Node As TreeNode
Public Depth As Integer
End Class 'RootViewNode
End Class 'GeneologyTree
End Namespace
using System;
using System.Collections;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Samples.AspNet.CS.Controls {
[AspNetHostingPermission(SecurityAction.Demand,
Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level=AspNetHostingPermissionLevel.Minimal)]
public class GeneologyTree : HierarchicalDataBoundControl {
private TreeNode rootNode;
public TreeNode RootNode {
get {
if (rootNode == null) {
rootNode = new TreeNode(String.Empty);
}
return rootNode;
}
}
private ArrayList nodes;
public ArrayList Nodes {
get {
if (null == nodes) {
nodes = new ArrayList();
}
return nodes;
}
}
public string DataTextField {
get {
object o = ViewState["DataTextField"];
return((o == null) ? string.Empty : (string)o);
}
set {
ViewState["DataTextField"] = value;
if (Initialized) {
OnDataPropertyChanged();
}
}
}
private int _maxDepth = 0;
protected override void PerformDataBinding() {
base.PerformDataBinding();
// Do not attempt to bind data if there is no
// data source set.
if (!IsBoundUsingDataSourceID && (DataSource == null)) {
return;
}
HierarchicalDataSourceView view = GetData(RootNode.DataPath);
if (view == null) {
throw new InvalidOperationException
("No view returned by data source control.");
}
IHierarchicalEnumerable enumerable = view.Select();
if (enumerable != null) {
Nodes.Clear();
try {
RecurseDataBindInternal(RootNode, enumerable, 1);
}
finally {
}
}
}
private void RecurseDataBindInternal(TreeNode node,
IHierarchicalEnumerable enumerable, int depth) {
foreach(object item in enumerable) {
IHierarchyData data = enumerable.GetHierarchyData(item);
if (null != data) {
// Create an object that represents the bound data
// to the control.
TreeNode newNode = new TreeNode();
RootViewNode rvnode = new RootViewNode();
rvnode.Node = newNode;
rvnode.Depth = depth;
// The dataItem is not just a string, but potentially
// an XML node or some other container.
// If DataTextField is set, use it to determine which
// field to render. Otherwise, use the first field.
if (DataTextField.Length > 0) {
newNode.Text = DataBinder.GetPropertyValue
(data, DataTextField, null);
}
else {
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(data);
// Set the "default" value of the node.
newNode.Text = String.Empty;
// Set the true data-bound value of the TextBox,
// if possible.
if (props.Count >= 1) {
if (null != props[0].GetValue(data)) {
newNode.Text =
props[0].GetValue(data).ToString();
}
}
}
Nodes.Add(rvnode);
if (data.HasChildren) {
IHierarchicalEnumerable newEnumerable =
data.GetChildren();
if (newEnumerable != null) {
RecurseDataBindInternal(newNode,
newEnumerable, depth+1 );
}
}
if ( _maxDepth < depth) _maxDepth = depth;
}
}
}
protected override void Render(HtmlTextWriter writer) {
writer.WriteLine("<PRE>");
int currentDepth = 1;
int currentTextLen = 0;
foreach (RootViewNode rvnode in Nodes) {
if (rvnode.Depth == currentDepth) {
string output = " " + rvnode.Node.Text + " ";
writer.Write(output);
currentTextLen = currentTextLen + output.Length;
}
else {
writer.WriteLine("");
// Some very basic whitespace formatting
int halfLine = currentTextLen / 2;
for (int i=0;i<halfLine;i++) {
writer.Write(' ');
}
writer.Write('|');
writer.WriteLine("");
++currentDepth;
currentTextLen = 0;
for (int j=0;j<halfLine;j++) {
writer.Write(' ');
}
string output = " " + rvnode.Node.Text + " ";
writer.Write(output);
currentTextLen = currentTextLen + output.Length;
}
}
writer.WriteLine("</PRE>");
}
private class RootViewNode {
public TreeNode Node;
public int Depth;
}
}
}
L'exemple de code suivant montre comment utiliser le contrôle GeneologyTree, défini dans l'exemple précédent, et le lier à un contrôle XmlDataSource.
<%@Page language="VB" %>
<%@ Register TagPrefix="aspSample"
Namespace="Samples.AspNet.VB.Controls"
Assembly="Samples.AspNet.VB.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>VB Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<aspSample:geneologytree
id="GeneologyTree1"
runat="server"
datatextfield="title"
datasourceid="XmlDataSource1" />
<asp:xmldatasource
id="XmlDataSource1"
datafile="geneology.xml"
runat="server" />
</form>
</body>
</html>
<%@Page language="c#" %>
<%@ Register TagPrefix="aspSample"
Namespace="Samples.AspNet.CS.Controls"
Assembly="Samples.AspNet.CS.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<aspSample:geneologytree
id="GeneologyTree1"
runat="server"
datatextfield="title"
datasourceid="XmlDataSource1" />
<asp:xmldatasource
id="XmlDataSource1"
datafile="geneology.xml"
runat="server" />
</form>
</body>
</html>
Le fichier geneology.xml qui fait l'objet d'un accès dans l'exemple de code contient les données suivantes.
<family>
<member title="great-grandfather">
<member title="grandfather" >
<member title="child" />
<member title="father" >
<member title="son" />
</member>
</member>
</member>
</family>

Informations de version
.NET FrameworkPris en charge dans : 4, 3.5, 3.0, 2.0

Plateformes
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

Sécurité des threads
Tous les membres static ( Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Voir aussi
|