Export (0) Print
Expand All

TreeView Class

Displays hierarchical data, such as a table of contents, in a tree structure.

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

[ControlValuePropertyAttribute("SelectedValue")]
public class TreeView : HierarchicalDataBoundControl, IPostBackEventHandler, 
	IPostBackDataHandler, ICallbackEventHandler
<asp:TreeView />

The TreeView type exposes the following members.

  NameDescription
Public methodTreeViewInitializes a new instance of the TreeView class.
Top

  NameDescription
Public propertyAccessKeyGets or sets the access key that allows you to quickly navigate to the Web server control. (Inherited from WebControl.)
Protected propertyAdapterGets the browser-specific adapter for the control. (Inherited from Control.)
Public propertyAppRelativeTemplateSourceDirectoryGets or sets the application-relative virtual directory of the Page or UserControl object that contains this control. (Inherited from Control.)
Public propertyAttributesGets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control. (Inherited from WebControl.)
Public propertyAutoGenerateDataBindingsGets or sets a value indicating whether the TreeView control automatically generates tree node bindings.
Public propertyBackColorGets or sets the background color of the Web server control. (Inherited from WebControl.)
Public propertyBindingContainerInfrastructure. Gets the control that contains this control's data binding. (Inherited from Control.)
Public propertyBorderColorGets or sets the border color of the Web control. (Inherited from WebControl.)
Public propertyBorderStyleGets or sets the border style of the Web server control. (Inherited from WebControl.)
Public propertyBorderWidthGets or sets the border width of the Web server control. (Inherited from WebControl.)
Public propertyCheckedNodesGets a collection of TreeNode objects that represent the nodes in the TreeView control that display a selected check box.
Protected propertyChildControlsCreatedGets a value that indicates whether the server control's child controls have been created. (Inherited from Control.)
Public propertyClientIDGets the control ID for HTML markup that is generated by ASP.NET. (Inherited from Control.)
Public propertyClientIDModeGets or sets the algorithm that is used to generate the value of the ClientID property. (Inherited from Control.)
Protected propertyClientIDSeparatorGets a character value representing the separator character used in the ClientID property. (Inherited from Control.)
Public propertyCollapseImageToolTipGets or sets the ToolTip for the image that is displayed for the collapsible node indicator.
Public propertyCollapseImageUrlGets or sets the URL to a custom image for the collapsible node indicator.
Protected propertyContextGets the HttpContext object associated with the server control for the current Web request. (Inherited from Control.)
Public propertyControlsGets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy. (Inherited from Control.)
Public propertyControlStyleGets the style of the Web server control. This property is used primarily by control developers. (Inherited from WebControl.)
Public propertyControlStyleCreatedGets a value indicating whether a Style object has been created for the ControlStyle property. This property is primarily used by control developers. (Inherited from WebControl.)
Public propertyCssClassGets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client. (Inherited from WebControl.)
Public propertyDataBindingsGets a collection of TreeNodeBinding objects that define the relationship between a data item and the node that it is binding to.
Public propertyDataItemContainerGets a reference to the naming container if the naming container implements IDataItemContainer. (Inherited from Control.)
Public propertyDataKeysContainerGets a reference to the naming container if the naming container implements IDataKeysControl. (Inherited from Control.)
Public propertyDataSourceGets or sets the object from which the data-bound control retrieves its list of data items. (Inherited from BaseDataBoundControl.)
Public propertyDataSourceIDGets or sets the ID of the control from which the data-bound control retrieves its list of data items. (Inherited from HierarchicalDataBoundControl.)
Protected propertyDesignModeGets a value indicating whether a control is being used on a design surface. (Inherited from Control.)
Public propertyEnableClientScriptGets or sets a value indicating whether the TreeView control renders client-side script to handle expanding and collapsing events.
Public propertyEnabledGets or sets a value indicating whether the Web server control is enabled. (Inherited from WebControl.)
Public propertyEnableThemingGets or sets a value indicating whether themes apply to this control. (Inherited from WebControl.)
Public propertyEnableViewStateGets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client. (Inherited from Control.)
Protected propertyEventsGets a list of event handler delegates for the control. This property is read-only. (Inherited from Control.)
Public propertyExpandDepthGets or sets the number of levels that are expanded when a TreeView control is displayed for the first time.
Public propertyExpandImageToolTipGets or sets the ToolTip for the image that is displayed for the expandable node indicator.
Public propertyExpandImageUrlGets or sets the URL to a custom image for the expandable node indicator.
Public propertyFontGets the font properties associated with the Web server control. (Inherited from WebControl.)
Public propertyForeColorGets or sets the foreground color (typically the color of the text) of the Web server control. (Inherited from WebControl.)
Public propertyHasAttributesGets a value indicating whether the control has attributes set. (Inherited from WebControl.)
Protected propertyHasChildViewStateGets a value indicating whether the current server control's child controls have any saved view-state settings. (Inherited from Control.)
Public propertyHeightGets or sets the height of the Web server control. (Inherited from WebControl.)
Public propertyHoverNodeStyleGets a reference to the TreeNodeStyle object that allows you to set the appearance of a node when the mouse pointer is positioned over it.
Public propertyIDGets or sets the programmatic identifier assigned to the server control. (Inherited from Control.)
Protected propertyIdSeparatorInfrastructure. Gets the character used to separate control identifiers. (Inherited from Control.)
Public propertyImageSetGets or sets the group of images to use for the TreeView control.
Protected propertyInitializedGets a value indicating whether the data-bound control has been initialized. (Inherited from BaseDataBoundControl.)
Protected propertyIsBoundUsingDataSourceIDGets a value indicating whether the DataSourceID property is set. (Inherited from BaseDataBoundControl.)
Protected propertyIsChildControlStateClearedGets a value indicating whether controls contained within this control have control state. (Inherited from Control.)
Protected propertyIsDataBindingAutomaticGets a value that indicates whether data binding is automatic. (Inherited from BaseDataBoundControl.)
Protected propertyIsEnabledGets a value indicating whether the control is enabled. (Inherited from WebControl.)
Protected propertyIsTrackingViewStateGets a value that indicates whether the server control is saving changes to its view state. (Inherited from Control.)
Protected propertyIsUsingModelBindersWhen implemented in a derived class, gets a value that indicates whether the control is using model binders. (Inherited from BaseDataBoundControl.)
Protected propertyIsViewStateEnabledGets a value indicating whether view state is enabled for this control. (Inherited from Control.)
Public propertyLeafNodeStyleGets a reference to the TreeNodeStyle object that allows you to set the appearance of leaf nodes.
Public propertyLevelStylesGets a collection of Style objects that represent the node styles at the individual levels of the tree.
Public propertyLineImagesFolderGets or sets the path to a folder that contains the line images that are used to connect child nodes to parent nodes.
Protected propertyLoadViewStateByIDGets a value indicating whether the control participates in loading its view state by ID instead of index. (Inherited from Control.)
Public propertyMaxDataBindDepthGets or sets the maximum number of tree levels to bind to the TreeView control.
Public propertyNamingContainerGets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same Control.ID property value. (Inherited from Control.)
Public propertyNodeIndentGets or sets the indentation amount (in pixels) for the child nodes of the TreeView control.
Public propertyNodesGets a collection of TreeNode objects that represents the root nodes in the TreeView control.
Public propertyNodeStyleGets a reference to the TreeNodeStyle object that allows you to set the default appearance of the nodes in the TreeView control.
Public propertyNodeWrapGets or sets a value indicating whether text wraps in a node when the node runs out of space.
Public propertyNoExpandImageUrlGets or sets the URL to a custom image for the non-expandable node indicator.
Public propertyPageGets a reference to the Page instance that contains the server control. (Inherited from Control.)
Public propertyParentGets a reference to the server control's parent control in the page control hierarchy. (Inherited from Control.)
Public propertyParentNodeStyleGets a reference to the TreeNodeStyle object that allows you to set the appearance of parent nodes in the TreeView control.
Public propertyPathSeparatorGets or sets the character that is used to delimit the node values that are specified by the ValuePath property.
Public propertyPopulateNodesFromClientGets or sets a value indicating whether node data is populated on demand from the client.
Public propertyRenderingCompatibilityGets a value that specifies the ASP.NET version that rendered HTML will be compatible with. (Inherited from Control.)
Protected propertyRequiresDataBindingGets or sets a value indicating whether the DataBind method should be called. (Inherited from BaseDataBoundControl.)
Public propertyRootNodeStyleGets a reference to the TreeNodeStyle object that allows you to set the appearance of the root node in the TreeView control.
Public propertySelectedNodeGets a TreeNode object that represents the selected node in the TreeView control.
Public propertySelectedNodeStyleGets the TreeNodeStyle object that controls the appearance of the selected node in the TreeView control.
Public propertySelectedValueGets the value of the selected node.
Public propertyShowCheckBoxesGets or sets a value indicating which node types will display a check box in the TreeView control.
Public propertyShowExpandCollapseGets or sets a value indicating whether expansion node indicators are displayed.
Public propertyShowLinesGets or sets a value indicating whether lines connecting child nodes to parent nodes are displayed.
Public propertySiteGets information about the container that hosts the current control when rendered on a design surface. (Inherited from Control.)
Public propertySkinIDGets or sets the skin to apply to the control. (Inherited from WebControl.)
Public propertySkipLinkTextGets or sets a value that is used to render alternate text for screen readers to skip the content for the control.
Public propertyStyleGets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control. (Inherited from WebControl.)
Public propertySupportsDisabledAttributeGets a value that indicates whether the control should set the disabled attribute of the rendered HTML element to "disabled" when the control's IsEnabled property is false. (Inherited from BaseDataBoundControl.)
Public propertyTabIndexGets or sets the tab index of the Web server control. (Inherited from WebControl.)
Protected propertyTagKeyGets the System.Web.UI.HtmlTextWriterTag value for the TreeView control. (Overrides WebControl.TagKey.)
Protected propertyTagNameGets the name of the control tag. This property is used primarily by control developers. (Inherited from WebControl.)
Public propertyTargetGets or sets the target window or frame in which to display the Web page content that is associated with a node.
Public propertyTemplateControlGets or sets a reference to the template that contains this control. (Inherited from Control.)
Public propertyTemplateSourceDirectoryGets the virtual directory of the Page or UserControl that contains the current server control. (Inherited from Control.)
Public propertyToolTipGets or sets the text displayed when the mouse pointer hovers over the Web server control. (Inherited from WebControl.)
Public propertyUniqueIDGets the unique, hierarchically qualified identifier for the server control. (Inherited from Control.)
Public propertyValidateRequestModeGets or sets a value that indicates whether the control checks client input from the browser for potentially dangerous values. (Inherited from Control.)
Protected propertyViewStateGets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page. (Inherited from Control.)
Protected propertyViewStateIgnoresCaseGets a value that indicates whether the StateBag object is case-insensitive. (Inherited from Control.)
Public propertyViewStateModeGets or sets the view-state mode of this control. (Inherited from Control.)
Public propertyVisibleGets or sets a value indicating whether the control is rendered as UI on the page. (Overrides Control.Visible.)
Public propertyWidthGets or sets the width of the Web server control. (Inherited from WebControl.)
Top

  NameDescription
Protected methodAddAttributesToRenderAdds HTML attributes and styles that need to be rendered to the specified HtmlTextWriter control. (Overrides WebControl.AddAttributesToRender(HtmlTextWriter).)
Protected methodAddedControlCalled after a child control is added to the Controls collection of the Control object. (Inherited from Control.)
Protected methodAddParsedSubObjectNotifies 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.)
Public methodApplyStyleCopies 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.)
Public methodApplyStyleSheetSkinApplies the style properties defined in the page style sheet to the control. (Inherited from Control.)
Protected methodBeginRenderTracingBegins design-time tracing of rendering data. (Inherited from Control.)
Protected methodBuildProfileTreeInfrastructure. 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.)
Protected methodClearCachedClientIDInfrastructure. Sets the cached ClientID value to null. (Inherited from Control.)
Protected methodClearChildControlStateDeletes the control-state information for the server control's child controls. (Inherited from Control.)
Protected methodClearChildStateDeletes the view-state and control-state information for all the server control's child controls. (Inherited from Control.)
Protected methodClearChildViewStateDeletes the view-state information for all the server control's child controls. (Inherited from Control.)
Protected methodClearEffectiveClientIDModeInfrastructure. Sets the ClientIDMode property of the current control instance and of any child controls to Inherit. (Inherited from Control.)
Public methodCollapseAllCloses every node in the tree.
Protected methodConfirmInitStateSets the initialized state of the data-bound control. (Inherited from BaseDataBoundControl.)
Public methodCopyBaseAttributesCopies 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.)
Protected methodCreateChildControlsCalled 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.)
Protected methodCreateControlCollectionCreates a collection to store child controls. (Overrides Control.CreateControlCollection().)
Protected methodCreateControlStyleCreates 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.)
Protected methodCreateNodeInfrastructure. Returns a new instance of the TreeNode class. The CreateNode is a helper method.
Public methodDataBind()Calls the DataBind method of the base class. (Overrides BaseDataBoundControl.DataBind().)
Protected methodDataBind(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.)
Protected methodDataBindChildrenBinds a data source to the server control's child controls. (Inherited from Control.)
Public methodDisposeEnables a server control to perform final clean up before it is released from memory. (Inherited from Control.)
Protected methodEndRenderTracingEnds design-time tracing of rendering data. (Inherited from Control.)
Protected methodEnsureChildControlsDetermines whether the server control contains child controls. If it does not, it creates child controls. (Inherited from Control.)
Protected methodEnsureDataBoundCalls the DataBind method if the DataSourceID property is set and the data-bound control is marked to require binding. (Inherited from BaseDataBoundControl.)
Protected methodEnsureIDCreates an identifier for controls that do not have an identifier assigned. (Inherited from Control.)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodExpandAllOpens every node in the tree.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodFindControl(String)Searches the current naming container for a server control with the specified id parameter. (Inherited from Control.)
Protected methodFindControl(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.)
Public methodFindNodeRetrieves the TreeNode object in the TreeView control at the specified value path.
Public methodFocusSets input focus to a control. (Inherited from Control.)
Protected methodGetCallbackResultReturns the result of a callback event that targets a control.
Protected methodGetDataRetrieves a HierarchicalDataSourceView object that the data-bound control uses to perform data operations. (Inherited from HierarchicalDataBoundControl.)
Protected methodGetDataSourceRetrieves the IHierarchicalDataSource that the data-bound control is associated with, if any. (Inherited from HierarchicalDataBoundControl.)
Protected methodGetDesignModeStateInfrastructure. Gets design-time data for a control. (Inherited from Control.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetRouteUrl(Object)Gets the URL that corresponds to a set of route parameters. (Inherited from Control.)
Public methodGetRouteUrl(RouteValueDictionary)Gets the URL that corresponds to a set of route parameters. (Inherited from Control.)
Public methodGetRouteUrl(String, Object)Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.)
Public methodGetRouteUrl(String, RouteValueDictionary)Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetUniqueIDRelativeToReturns the prefixed portion of the UniqueID property of the specified control. (Inherited from Control.)
Public methodHasControlsDetermines if the server control contains any child controls. (Inherited from Control.)
Protected methodHasEventsReturns a value indicating whether events are registered for the control or any child controls. (Inherited from Control.)
Protected methodIsLiteralContentInfrastructure. Determines if the server control holds only literal content. (Inherited from Control.)
Protected methodLoadControlStateRestores control-state information from a previous page request that was saved by the SaveControlState method. (Inherited from Control.)
Protected methodLoadPostDataProcesses postback data for the TreeView control.
Protected methodLoadViewStateInfrastructure. Loads the previously saved view state of the TreeView control. (Overrides WebControl.LoadViewState(Object).)
Protected methodMapPathSecureRetrieves the physical path that a virtual path, either absolute or relative, maps to. (Inherited from Control.)
Protected methodMarkAsDataBoundSets the state of the control in view state as successfully bound to data. (Inherited from HierarchicalDataBoundControl.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodMergeStyleCopies 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.)
Protected methodOnBubbleEventDetermines whether the event for the server control is passed up the page's UI server control hierarchy. (Inherited from Control.)
Protected methodOnDataBindingRaises the DataBinding event. (Inherited from Control.)
Protected methodOnDataBoundRaises the DataBound event. (Inherited from BaseDataBoundControl.)
Protected methodOnDataPropertyChangedCalled when one of the base data source identification properties is changed, to re-bind the data-bound control to its data. (Inherited from HierarchicalDataBoundControl.)
Protected methodOnDataSourceChangedCalled when the IHierarchicalDataSource instance that the data-bound control works with raises the DataSourceChanged event. (Inherited from HierarchicalDataBoundControl.)
Protected methodOnInitRaises the Init event. (Overrides BaseDataBoundControl.OnInit(EventArgs).)
Protected methodOnLoadHandles the Load event. (Inherited from HierarchicalDataBoundControl.)
Protected methodOnPagePreLoadSets the initialized state of the data-bound control before the control is loaded. (Inherited from HierarchicalDataBoundControl.)
Protected methodOnPreRenderRaises the Control.PreRender event. (Overrides BaseDataBoundControl.OnPreRender(EventArgs).)
Protected methodOnSelectedNodeChangedRaises the SelectedNodeChanged event of the TreeView control.
Protected methodOnTreeNodeCheckChangedRaises the TreeNodeCheckChanged event of the TreeView control.
Protected methodOnTreeNodeCollapsedRaises the TreeNodeCollapsed event of the TreeView control.
Protected methodOnTreeNodeDataBoundRaises the TreeNodeDataBound event of the TreeView control.
Protected methodOnTreeNodeExpandedRaises the TreeNodeExpanded event of the TreeView control.
Protected methodOnTreeNodePopulateRaises the TreeNodePopulate event of the TreeView control.
Protected methodOnUnloadRaises the Unload event. (Inherited from Control.)
Protected methodOpenFileGets a Stream used to read a file. (Inherited from Control.)
Protected methodPerformDataBindingInfrastructure. Creates all the nodes based on the data source. (Overrides HierarchicalDataBoundControl.PerformDataBinding().)
Protected methodPerformSelectRetrieves data from the associated data source. (Inherited from HierarchicalDataBoundControl.)
Protected methodRaiseBubbleEventAssigns any sources of the event and its information to the control's parent. (Inherited from Control.)
Protected methodRaiseCallbackEventInfrastructure. Raises the callback event using the specified arguments.
Protected methodRaisePostBackEventEnables the TreeView control to process an event that is raised when a form is posted to the server. The RaisePostBackEvent method is a helper method for the ICallbackEventHandler.RaiseCallbackEvent method.
Protected methodRaisePostDataChangedEventInfrastructure. Signals the TreeView control to notify the ASP.NET application that the state of the control has changed.
Protected methodRemovedControlCalled after a child control is removed from the Controls collection of the Control object. (Inherited from Control.)
Protected methodRenderRenders the control to the specified HTML writer. (Inherited from WebControl.)
Public methodRenderBeginTagRenders the HTML opening tag of the control to the specified writer. (Overrides WebControl.RenderBeginTag(HtmlTextWriter).)
Protected methodRenderChildrenOutputs 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.)
Protected methodRenderContentsRenders the nodes in the TreeView control. (Overrides WebControl.RenderContents(HtmlTextWriter).)
Public methodRenderControl(HtmlTextWriter)Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled. (Inherited from Control.)
Protected methodRenderControl(HtmlTextWriter, ControlAdapter)Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object. (Inherited from Control.)
Public methodRenderEndTagRenders the HTML closing tag of the control to the specified writer. (Overrides WebControl.RenderEndTag(HtmlTextWriter).)
Protected methodResolveAdapterGets the control adapter responsible for rendering the specified control. (Inherited from Control.)
Public methodResolveClientUrlGets a URL that can be used by the browser. (Inherited from Control.)
Public methodResolveUrlConverts a URL into one that is usable on the requesting client. (Inherited from Control.)
Protected methodSaveControlStateSaves any server control state changes that have occurred since the time the page was posted back to the server. (Inherited from Control.)
Protected methodSaveViewStateInfrastructure. Saves the state of the TreeView control. (Overrides WebControl.SaveViewState().)
Protected methodSetDesignModeStateSets design-time data for a control. (Inherited from Control.)
Protected methodSetNodeDataBoundAllows a derived class to set whether the specified TreeNode control is data-bound.
Protected methodSetNodeDataItemAllows a derived class to set the data item for the specified TreeNode control.
Protected methodSetNodeDataPathAllows a derived class to set the data path for the specified TreeNode control.
Public methodSetRenderMethodDelegateInfrastructure. Assigns an event handler delegate to render the server control and its content into its parent control. (Inherited from Control.)
Public methodSetTraceData(Object, Object)Sets trace data for design-time tracing of rendering data, using the trace data key and the trace data value. (Inherited from Control.)
Public methodSetTraceData(Object, Object, Object)Sets trace data for design-time tracing of rendering data, using the traced object, the trace data key, and the trace data value. (Inherited from Control.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Protected methodTrackViewStateInfrastructure. Tracks view-state changes to the TreeView control so that they can be stored in the System.Web.UI.StateBag object for the control. This System.Web.UI.StateBag is accessible through the Control.ViewState property. (Overrides WebControl.TrackViewState().)
Protected methodValidateDataSourceVerifies that the object a data-bound control binds to is one it can work with. (Inherited from HierarchicalDataBoundControl.)
Top

  NameDescription
Public eventDataBindingOccurs when the server control binds to a data source. (Inherited from Control.)
Public eventDataBoundOccurs after the server control binds to a data source. (Inherited from BaseDataBoundControl.)
Public eventDisposedOccurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested. (Inherited from Control.)
Public eventInitOccurs when the server control is initialized, which is the first step in its lifecycle. (Inherited from Control.)
Public eventLoadOccurs when the server control is loaded into the Page object. (Inherited from Control.)
Public eventPreRenderOccurs after the Control object is loaded but prior to rendering. (Inherited from Control.)
Public eventSelectedNodeChangedOccurs when a node is selected in the TreeView control.
Public eventTreeNodeCheckChangedOccurs when a check box in the TreeView control changes state between posts to the server.
Public eventTreeNodeCollapsedOccurs when a node is collapsed in the TreeView control.
Public eventTreeNodeDataBoundOccurs when a data item is bound to a node in the TreeView control.
Public eventTreeNodeExpandedOccurs when a node is expanded in the TreeView control.
Public eventTreeNodePopulateOccurs when a node with its PopulateOnDemand property set to true is expanded in the TreeView control.
Public eventUnloadOccurs when the server control is unloaded from memory. (Inherited from Control.)
Top

  NameDescription
Public Extension MethodEnablePersistedSelectionEnables selection to be persisted in data controls that support selection and paging. (Defined by DynamicDataExtensions.)
Public Extension MethodFindDataSourceControlReturns the data source that is associated with the data control for the specified control. (Defined by DynamicDataExtensions.)
Public Extension MethodFindFieldTemplateReturns the field template for the specified column in the specified control's naming container. (Defined by DynamicDataExtensions.)
Public Extension MethodFindMetaTableReturns the metatable object for the containing data control. (Defined by DynamicDataExtensions.)
Top

  NameDescription
Explicit interface implemetationPrivate methodIAttributeAccessor.GetAttributeInfrastructure. Gets an attribute of the Web control with the specified name. (Inherited from WebControl.)
Explicit interface implemetationPrivate methodIAttributeAccessor.SetAttributeSets an attribute of the Web control to the specified name and value. (Inherited from WebControl.)
Explicit interface implemetationPrivate methodICallbackEventHandler.GetCallbackResultInfrastructure. Returns the result of a callback event that targets a control.
Explicit interface implemetationPrivate methodICallbackEventHandler.RaiseCallbackEventInfrastructure. Raises the callback event using the specified arguments.
Explicit interface implemetationPrivate propertyIControlBuilderAccessor.ControlBuilderFor a description of this member, see IControlBuilderAccessor.ControlBuilder. (Inherited from Control.)
Explicit interface implemetationPrivate methodIControlDesignerAccessor.GetDesignModeStateFor a description of this member, see IControlDesignerAccessor.GetDesignModeState. (Inherited from Control.)
Explicit interface implemetationPrivate methodIControlDesignerAccessor.SetDesignModeStateFor a description of this member, see IControlDesignerAccessor.SetDesignModeState. (Inherited from Control.)
Explicit interface implemetationPrivate methodIControlDesignerAccessor.SetOwnerControlInfrastructure. For a description of this member, see IControlDesignerAccessor.SetOwnerControl. (Inherited from Control.)
Explicit interface implemetationPrivate propertyIControlDesignerAccessor.UserDataFor a description of this member, see IControlDesignerAccessor.UserData. (Inherited from Control.)
Explicit interface implemetationPrivate propertyIDataBindingsAccessor.DataBindingsFor a description of this member, see IDataBindingsAccessor.DataBindings. (Inherited from Control.)
Explicit interface implemetationPrivate propertyIDataBindingsAccessor.HasDataBindingsFor a description of this member, see IDataBindingsAccessor.HasDataBindings. (Inherited from Control.)
Explicit interface implemetationPrivate propertyIExpressionsAccessor.ExpressionsFor a description of this member, see IExpressionsAccessor.Expressions. (Inherited from Control.)
Explicit interface implemetationPrivate propertyIExpressionsAccessor.HasExpressionsFor a description of this member, see IExpressionsAccessor.HasExpressions. (Inherited from Control.)
Explicit interface implemetationPrivate methodIParserAccessor.AddParsedSubObjectFor a description of this member, see IParserAccessor.AddParsedSubObject. (Inherited from Control.)
Explicit interface implemetationPrivate methodIPostBackDataHandler.LoadPostDataInfrastructure. Processes postback data for the TreeView control.
Explicit interface implemetationPrivate methodIPostBackDataHandler.RaisePostDataChangedEventInfrastructure. Signals the TreeView control to notify the ASP.NET application that the state of the control has changed.
Explicit interface implemetationPrivate methodIPostBackEventHandler.RaisePostBackEventInfrastructure. Enables the TreeView control to process an event that is raised when a form is posted to the server.
Top

In this topic:

Introduction

The TreeView control is used to display hierarchical data, such as a table of contents or file directory, in a tree structure and supports the following features:

  • Data binding that allows the nodes of the control to be bound to XML, tabular, or relational data.

  • Site navigation through integration with the SiteMapDataSource control.

  • Node text that can be displayed as either plain text or hyperlinks.

  • Programmatic access to the TreeView object model to create trees, populate nodes, set properties, and so on dynamically.

  • Client-side node population (on supported browsers).

  • The ability to display a check box next to each node.

  • Customizable appearance through themes, user-defined images, and styles.

    NoteNote

    The TreeView control is designed to be used inside an UpdatePanel control only when EnableClientScript is set to true. UpdatePanel controls are used to update selected regions of a page instead of updating the whole page with a postback. For more information, see UpdatePanel Control Overview and Partial-Page Rendering Overview.

Nodes

The TreeView control is made up of nodes. Each entry in the tree is called a node and is represented by a TreeNode object. Node types are defined as follows:

  • A node that contains other nodes is called a parent node.

  • The node that is contained by another node is called a child node.

  • A node that has no children is called a leaf node.

  • The node that is not contained by any other node but is the ancestor to all the other nodes is the root node.

A node can be both a parent and a child, but root, parent, and leaf nodes are mutually exclusive. Several visual and behavioral properties of nodes are determined by whether a node is a root, child, or leaf node.

Although a typical tree structure has only one root node, the TreeView control allows you to add multiple root nodes to your tree structure. This is useful when you want to display item listings without displaying a single root node, as in a list of product categories.

Each node has a Text property and a Value property. The value of the Text property is displayed in the TreeView, while the Value property is used to store any additional data about the node, such as data that is passed to the postback event that is associated with the node.

A node can be in one of two modes: selection mode and navigation mode. By default, a node is in selection mode. To put a node into navigation mode, set the NavigateUrl property for the node to a value other than an empty string (""). To put a node into selection mode, set the NavigateUrl property for the node to an empty string ("").

NoteNote

Some Internet browsers have a limitation that can affect the performance of the TreeView control. For example, Microsoft Internet Explorer 6.0 has a URL character limit of 2067 characters that it posts. If the number of characters in a URL of a node is larger than that number, expanding that node will fail and no exception is thrown.

Static Data

The simplest data model of the TreeView control is static data. To display static data using declarative syntax, first nest opening and closing <Nodes> tags between the opening and closing tags of the TreeView control. Next, create the tree structure by nesting <asp:TreeNode> elements between the opening and closing <Nodes> tags. Each <asp:TreeNode> element represents a node in the tree and maps to a TreeNode object. You can set the properties of each node by setting the attributes of its <asp:TreeNode> element. To create child nodes, nest additional <asp:TreeNode> elements between the opening and closing <asp:TreeNode> tags of the parent node.

Binding to Data

The TreeView control can also be bound to data. You can use either of two methods to bind the TreeView control to the appropriate data source type:

  • The TreeView control can use any data source control that implements the IHierarchicalDataSource interface, such as an XmlDataSource control or a SiteMapDataSource control. To bind to a data source control, set the DataSourceID property of the TreeView control to the ID value of the data source control. The TreeView control automatically binds to the specified data source control. This is the preferred method to bind to data.

  • The TreeView control can also be bound to an XmlDocument object or a DataSet object with relations. To bind to one of these data sources, set the DataSource property of the TreeView control to the data source, and then call the DataBind method.

When binding to a data source where each data item contains multiple properties (such as an XML element with several attributes), a node displays the value that is returned by the ToString method of the data item, by default. In the case of an XML element, the node displays the element name, which shows the underlying structure of the tree but is not very useful otherwise. You can bind a node to a specific data item property by specifying tree node bindings using the DataBindings collection. The DataBindings collection contains TreeNodeBinding objects that define the relationship between a data item and the node that it is binding to. You can specify the criteria for binding and the data item property to display in the node. For more information on tree node bindings, see TreeNodeBinding.

Security noteSecurity Note

A malicious user can create a callback request and get data for the nodes of the TreeView control that the page developer is not displaying. Therefore, security of the data must be implemented by the data source. Do not use the MaxDataBindDepth property to hide data.

Dynamic Node Population

Sometimes, it is not practical to statically define the tree structure because the data source returns too much data or because the data to display depends on information that you get at run time. Because of this, the TreeView control supports dynamic node population. When the PopulateOnDemand property for a node is set to true, that node gets populated at run time when the node is expanded. To populate a node dynamically, you must define an event-handling method that contains the logic to populate a node for the TreeNodePopulate event.

Browsers that support callback scripts can also take advantage of client-side node population. (This includes Internet Explorer 5.5 and later and some other browsers.) Client-side node population enables the TreeView control to populate a node using client script when users expand the node, without requiring a round trip to the server. For more information on client-side node population, see PopulateNodesFromClient.

Customizing the User Interface

There are many ways to customize the appearance of the TreeView control. First, you can specify a different style (such as font size and color) for each of the node types.

If you use cascading style sheets (CSS) to customize the appearance of the control, use either inline styles or a separate CSS file, but not both. Using both inline styles and a separate CSS file could cause unexpected results. For more information on using style sheets with controls, see ASP.NET Web Server Controls and CSS Styles.

The following table lists the available node styles.

Node style property

Description

HoverNodeStyle

The style settings for a node when the mouse pointer is positioned over it.

LeafNodeStyle

The style settings for the leaf nodes.

NodeStyle

The default style settings for a node.

ParentNodeStyle

The style settings for the parent nodes.

RootNodeStyle

The style settings for the root node.

SelectedNodeStyle

The style settings for a selected node.

You can also control the style of nodes at specific depths within the tree by using the LevelStyles collection. The first style in the collection corresponds to the style of the nodes at the first level in the tree. The second style in the collection corresponds to the style of the nodes at the second level in the tree, and so on. This is most often used to generate table of contents–style navigation menus where nodes at a certain depth should have the same appearance, regardless of whether they have child nodes.

NoteNote

If a style is defined for a certain depth level using the LevelStyles collection, that style overrides any root, parent, or leaf node style settings for the nodes at that depth.

Another way to alter the appearance of the control is to customize the images that are displayed in the TreeView control. You can specify your own custom set of images for the different parts of the control by setting the properties shown in the following table.

Image property

Description

CollapseImageUrl

The URL to an image displayed for the collapsible node indicator. This image is usually a minus sign (-).

ExpandImageUrl

The URL to an image displayed for the expandable node indicator. This image is usually a plus sign (+).

LineImagesFolder

The URL to the folder containing the line images used to connect parent nodes to child nodes. The ShowLines property must also be set to true for this property to have an effect.

NoExpandImageUrl

The URL to an image displayed for the non-expandable node indicator.

NoteNote

You do not need to customize every image property. If an image property is not explicitly set, the built-in default image is used.

The TreeView control also allows you to display a check box next to a node. When the ShowCheckBoxes property is set to a value other than TreeNodeTypes.None, check boxes are displayed next to the specified node types.

NoteNote

The ShowCheckBoxes property can be set to a bitwise combination of the TreeNodeTypes enumeration member values.

Each time the page is posted to the server, the CheckedNodes collection is automatically populated with the selected nodes. When check boxes are displayed, you can use the TreeNodeCheckChanged event to run a custom routine whenever the state of a check box changes between posts to the server.

Events

The TreeView control provides several events that you can program against. This allows you to run a custom routine whenever an event occurs. The following table lists the events that are supported by the TreeView control.

Event

Description

TreeNodeCheckChanged

Occurs when the check boxes of the TreeView control change state between posts to the server.

SelectedNodeChanged

Occurs when a node is selected in the TreeView control.

TreeNodeExpanded

Occurs when a node is expanded in the TreeView control.

TreeNodeCollapsed

Occurs when a node is collapsed in the TreeView control.

TreeNodePopulate

Occurs when a node with its PopulateOnDemand property set to true is expanded in the TreeView control.

TreeNodeDataBound

Occurs when a data item is bound to a node in the TreeView control.

Scrolling

The TreeView control does not have built-in scrolling. To add scrolling, place the TreeView control in a Panel control and add scrollbars to the Panel control. For more information, see Panel Web Server Control Overview.

Accessibility

The markup rendered by default for this control might not conform to accessibility standards. For details about accessibility support for this control, see ASP.NET Controls and Accessibility.

Declarative Syntax

<asp:TreeView
    AccessKey="string"
    AutoGenerateDataBindings="True|False"
    BackColor="color name|#dddddd"
    BorderColor="color name|#dddddd"
    BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
        Inset|Outset"
    BorderWidth="size"
    CollapseImageToolTip="string"
    CollapseImageUrl="uri"
    CssClass="string"
    DataSource="string"
    DataSourceID="string"
    EnableClientScript="True|False"
    Enabled="True|False"
    EnableTheming="True|False"
    EnableViewState="True|False"
    ExpandDepth="string|FullyExpand|0|1|2|3|4|5|6|7|8|9|10|11|12|13|
        14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30"
    ExpandImageToolTip="string"
    ExpandImageUrl="uri"
    Font-Bold="True|False"
    Font-Italic="True|False"
    Font-Names="string"
    Font-Overline="True|False"
    Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
       Large|X-Large|XX-Large"
    Font-Strikeout="True|False"
    Font-Underline="True|False"
    ForeColor="color name|#dddddd"
    Height="size"
    ID="string"
    ImageSet="Custom|XPFileExplorer|Msdn|WindowsHelp|Simple|Simple2|
        BulletedList|BulletedList2|BulletedList3|BulletedList4|
        Arrows|News|Contacts|Inbox|Events|Faq"
    LineImagesFolder="string"
    MaxDataBindDepth="integer"
    NodeIndent="integer"
    NodeWrap="True|False"
    NoExpandImageUrl="uri"
    OnDataBinding="DataBinding event handler"
    OnDataBound="DataBound event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnLoad="Load event handler"
    OnPreRender="PreRender event handler"
    OnSelectedNodeChanged="SelectedNodeChanged event handler"
    OnTreeNodeCheckChanged="TreeNodeCheckChanged event handler"
    OnTreeNodeCollapsed="TreeNodeCollapsed event handler"
    OnTreeNodeDataBound="TreeNodeDataBound event handler"
    OnTreeNodeExpanded="TreeNodeExpanded event handler"
    OnTreeNodePopulate="TreeNodePopulate event handler"
    OnUnload="Unload event handler"
    PathSeparator="string"
    PopulateNodesFromClient="True|False"
    runat="server"
    ShowCheckBoxes="None|Root|Parent|Leaf|All"
    ShowExpandCollapse="True|False"
    ShowLines="True|False"
    SkinID="string"
    SkipLinkText="string"
    Style="string"
    TabIndex="integer"
    Target="string"
    ToolTip="string"
    Visible="True|False"
    Width="size"
>
        <DataBindings>
                <asp:TreeNodeBinding
                    DataMember="string"
                    Depth="integer"
                    FormatString="string"
                    ImageToolTip="string"
                    ImageToolTipField="string"
                    ImageUrl="uri"
                    ImageUrlField="string"
                    NavigateUrl="uri"
                    NavigateUrlField="string"
                    PopulateOnDemand="True|False"
                    SelectAction="Select|Expand|SelectExpand|None"
                    ShowCheckBox="string"
                    Target="string"
                    TargetField="string"
                    Text="string"
                    TextField="string"
                    ToolTip="string"
                    ToolTipField="string"
                    Value="string"
                    ValueField="string"
                />
        </DataBindings>
        <HoverNodeStyle />
        <LeafNodeStyle
            BackColor="color name|#dddddd"
            BorderColor="color name|#dddddd"
            BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|
                Groove|Ridge|Inset|Outset"
            BorderWidth="size"
            ChildNodesPadding="size"
            CssClass="string"
            Font-Bold="True|False"
            Font-Italic="True|False"
            Font-Names="string"
            Font-Overline="True|False"
            Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|
                Medium|Large|X-Large|XX-Large"
            Font-Strikeout="True|False"
            Font-Underline="True|False"
            ForeColor="color name|#dddddd"
            Height="size"
            HorizontalPadding="size"
            ImageUrl="uri"
            NodeSpacing="size"
            OnDisposed="Disposed event handler"
            VerticalPadding="size"
            Width="size"
        />
        <LevelStyles>
                <asp:TreeNodeStyle
                    BackColor="color name|#dddddd"
                    BorderColor="color name|#dddddd"
                    BorderStyle="NotSet|None|Dotted|Dashed|Solid|
                        Double|Groove|Ridge|Inset|Outset"
                    BorderWidth="size"
                    ChildNodesPadding="size"
                    CssClass="string"
                    Font-Bold="True|False"
                    Font-Italic="True|False"
                    Font-Names="string"
                    Font-Overline="True|False"
                    Font-Size="string|Smaller|Larger|XX-Small|
                        X-Small|Small|Medium|Large|X-Large|XX-Large"
                    Font-Strikeout="True|False"
                    Font-Underline="True|False"
                    ForeColor="color name|#dddddd"
                    Height="size"
                    HorizontalPadding="size"
                    ImageUrl="uri"
                    NodeSpacing="size"
                    OnDisposed="Disposed event handler"
                    VerticalPadding="size"
                    Width="size"
                />
        </LevelStyles>
        <Nodes>
                <asp:TreeNode
                    Checked="True|False"
                    Expanded="string"
                    ImageToolTip="string"
                    ImageUrl="uri"
                    NavigateUrl="uri"
                    PopulateOnDemand="True|False"
                    SelectAction="Select|Expand|SelectExpand|None"
                    Selected="True|False"
                    ShowCheckBox="string"
                    Target="string"
                    Text="string"
                    ToolTip="string"
                    Value="string"
>
                </asp:TreeNode>
        </Nodes>
        <NodeStyle
            BackColor="color name|#dddddd"
            BorderColor="color name|#dddddd"
            BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|
                Groove|Ridge|Inset|Outset"
            BorderWidth="size"
            ChildNodesPadding="size"
            CssClass="string"
            Font-Bold="True|False"
            Font-Italic="True|False"
            Font-Names="string"
            Font-Overline="True|False"
            Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|
                Medium|Large|X-Large|XX-Large"
            Font-Strikeout="True|False"
            Font-Underline="True|False"
            ForeColor="color name|#dddddd"
            Height="size"
            HorizontalPadding="size"
            ImageUrl="uri"
            NodeSpacing="size"
            OnDisposed="Disposed event handler"
            VerticalPadding="size"
            Width="size"
        />
        <ParentNodeStyle
            BackColor="color name|#dddddd"
            BorderColor="color name|#dddddd"
            BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|
                Groove|Ridge|Inset|Outset"
            BorderWidth="size"
            ChildNodesPadding="size"
            CssClass="string"
            Font-Bold="True|False"
            Font-Italic="True|False"
            Font-Names="string"
            Font-Overline="True|False"
            Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|
                Medium|Large|X-Large|XX-Large"
            Font-Strikeout="True|False"
            Font-Underline="True|False"
            ForeColor="color name|#dddddd"
            Height="size"
            HorizontalPadding="size"
            ImageUrl="uri"
            NodeSpacing="size"
            OnDisposed="Disposed event handler"
            VerticalPadding="size"
            Width="size"
        />
        <RootNodeStyle
            BackColor="color name|#dddddd"
            BorderColor="color name|#dddddd"
            BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|
                Groove|Ridge|Inset|Outset"
            BorderWidth="size"
            ChildNodesPadding="size"
            CssClass="string"
            Font-Bold="True|False"
            Font-Italic="True|False"
            Font-Names="string"
            Font-Overline="True|False"
            Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|
                Medium|Large|X-Large|XX-Large"
            Font-Strikeout="True|False"
            Font-Underline="True|False"
            ForeColor="color name|#dddddd"
            Height="size"
            HorizontalPadding="size"
            ImageUrl="uri"
            NodeSpacing="size"
            OnDisposed="Disposed event handler"
            VerticalPadding="size"
            Width="size"
        />
        <SelectedNodeStyle
            BackColor="color name|#dddddd"
            BorderColor="color name|#dddddd"
            BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|
                Groove|Ridge|Inset|Outset"
            BorderWidth="size"
            ChildNodesPadding="size"
            CssClass="string"
            Font-Bold="True|False"
            Font-Italic="True|False"
            Font-Names="string"
            Font-Overline="True|False"
            Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|
                Medium|Large|X-Large|XX-Large"
            Font-Strikeout="True|False"
            Font-Underline="True|False"
            ForeColor="color name|#dddddd"
            Height="size"
            HorizontalPadding="size"
            ImageUrl="uri"
            NodeSpacing="size"
            OnDisposed="Disposed event handler"
            VerticalPadding="size"
            Width="size"
        />
</asp:TreeView>
TopicLocation
How to: Programmatically Enumerate Site-Map NodesBuilding ASP .NET Web Applications
How to: Configure Multiple Site Maps and Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server ControlsBuilding ASP .NET Web Applications
How to: Customize the Appearance of SiteMapPath Web Server ControlsBuilding ASP .NET Web Applications
How to: Display Site-Map Data in Non-Hierarchical Web Server ControlsBuilding ASP .NET Web Applications
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications
How to: Implement ASP.NET Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Programmatically Enumerate Site-Map NodesBuilding ASP .NET Web Applications
How to: Configure Multiple Site Maps and Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server ControlsBuilding ASP .NET Web Applications
How to: Customize the Appearance of SiteMapPath Web Server ControlsBuilding ASP .NET Web Applications
How to: Display Site-Map Data in Non-Hierarchical Web Server ControlsBuilding ASP .NET Web Applications
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications
How to: Implement ASP.NET Site-Map ProvidersBuilding ASP .NET Web Applications
Walkthrough: Adding Site Navigation to a Web SiteBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Customizing a Web Site Using Themes in Visual StudioBuilding ASP .NET Web Applications in Visual Studio
How to: Add or Delete TreeView Node Elements (Visual Studio)Building ASP .NET Web Applications in Visual Studio
Walkthrough: Displaying Hierarchical Data in a TreeView ControlBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Filtering Site-Map Nodes Based on Security RolesBuilding ASP .NET Web Applications in Visual Studio

This section contains seven code examples:

  • The first code example demonstrates how to set up the frames for the second code example.

  • The second code example demonstrates how to use declarative syntax to display static data in the TreeView control.

  • The third code example demonstrates how to bind the TreeView control to an XML data source.

  • The fourth code example provides sample XML data for the third code example.

  • The fifth code example demonstrates how to use the TreeView control for site navigation by binding it to a SiteMapDataSource control.

  • The sixth code example provides sample site map data for the fifth code example.

  • The seventh code example demonstrates how to populate the nodes in the TreeView control from the client.

The following code example demonstrates how to set up the frames for the following code example.


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>TreeView Frameset Example</title>
</head>

    <frameset cols="30%, 75%">

        <frame title="MenuFrame" name="Menu" src="TreeViewFramecs.aspx"/>
        <frame title="ContentFrame" name="Content" src="Home.aspx"/> 

    </frameset>      

</html>

The following code example demonstrates how to use declarative syntax to display static data in the TreeView control. This example is used within the frame set of the preceding example to display a table of contents.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>TreeView Declarative Syntax Example</title>
</head>
<body>
    <form id="form1" 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>

The following code example demonstrates how to bind the TreeView control to an XML data source. For this example to work correctly, you must copy the sample XML data, provided after this code example, to a file named Book.xml.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>TreeView XML Data Binding Example</title>
</head>
<body>
    <form id="form1" 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>

The following code example provides sample XML data for the preceding example.

<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>

The following code example demonstrates how to use the TreeView control for site navigation by binding it to a SiteMapDataSource control. For this example to work correctly, you must copy the sample site map data, provided after this code example, to a file named Web.sitemap.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>TreeView AutoGenerateBindings Example</title>
</head>
<body>
    <form id="form1" 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>

The following code example provides sample site map data for the preceding code example.

<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>

The following code example demonstrates how to populate the nodes in the TreeView control from the client. When client-side node population is enabled, nodes are populated dynamically on the client, without the need to post back to the server.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>TreeView PopulateNodesFromClient Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>TreeView PopulateNodesFromClient Example</h3>

      <asp:TreeView id="LinksTreeView"
        Font-Names= "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

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft