Click here to Skip to main content
13,897,583 members
Click here to Skip to main content
Add your own
alternative version


65 bookmarked
Posted 16 Apr 2007
Licenced CPOL

Auto Binding a TreeView control from a self referencing table

, 16 Apr 2007
Rate this:
Please Sign up or sign in to vote.
A Custom TreeView Control that supports auto binding from a single self referencing table
Screenshot - AutoBindingTreeView.gif


This article will show how to implement a custom ASP.NET TreeView control that supports auto binding from a self referencing table. The control supports binding from a Data Source control or programmatically using the Data Source property.


This article is a continuation to my previous article showing useful functionalities that the TreeView control lacks. The previous article demonstrated applying CSS and adding custom attributes to tree nodes. In this article, Auto Binding a TreeView control from a Self Referencing Table is discussed.

What is a Self Referencing Table?

A self referencing table contains a relation where one of its columns references another column in the same table. For example:

Self Referencing table

In the figure above, Parent ID column references the ID column meaning that the Parent ID is an ID forming hierarchical data.

Auto Binding

ASP.NET TreeView only supports hierarchical datasource controls. To work around that, we create a data-bound control class AutoBindingTree that extends the base class DataBoundControl so that we can override PerformSelect and PerformDataBinding events. Click here for more information on creating custom data-bound controls.

The PerformDataBinding takes an IEnumerable as a parameter representing the Data retrieved from the Data Source. This parameter is used to create a DataView since it implements IEnumerable.The DataView is then use to create a DataSet that maintains the Self Reference Relationship and is then used to populate the TreeView. The DataSet uses three mandatory properties:

  1. DataTextField: The name of the column holding the Node Text Value
  2. DataFieldID: The name of the Column holding the ID value
  3. DataFieldParentID: The name of the Column holding the ParentID value
Protected Overrides Sub PerformDataBinding(ByVal oSourceData As IEnumerable)

    ' Verify data exists.
    If Not (oSourceData Is Nothing) Then
    Dim oView As DataView = oSourceData
    Dim oTable As DataTable = oView.Table
    Dim oDS As DataSet = New DataSet()

        'Create a Relation Between the ID Column and Parent Column
        If oDS.Relations.Contains("SelfRefenceRelation") = False Then
        oDS.Relations.Add("SelfRefenceRelation", _
            oDS.Tables(0).Columns(DataFieldID), _
        End If

        oTable = Nothing

        ViewState("TreeData") = oDS

        oDS = Nothing
    End If
        End Sub

Once the DataSet is created, LoadTreeView is called to populate the Treeview:

Private Sub LoadTreeView(ByVal oDS As DataSet)
    Dim oTreeView As TreeView = New TreeView()
    Dim oDataRow As DataRow
    For Each oDataRow In oDS.Tables(0).Rows
        'Find Root Node,A root node has ParentID NULL
        If oDataRow.IsNull(DataFieldParentID) Then
        'Create Parent Node and add to tree
        Dim oNode As New TreeNode()
        oNode.Text = oDataRow(DataTextField).ToString()
        oNode.Value = oDataRow(DataFieldID).ToString()
        oNode.NavigateUrl = oDataRow("NavigateURL").ToString()

        'Recursively Populate From root
        RecursivelyLoadTree(oDataRow, oNode)
        End If
    Next oDataRow
    oDS = Nothing
End Sub 'LoadTreeView

First of all Root elements (ParentID = NULL) are identified, added to the tree and then the function RecursivelyLoadTree is called to recursively create child elements:

Private Sub RecursivelyLoadTree(ByVal oDataRow As DataRow, _
    ByRef oNode As TreeNode)
    Dim oChildRow As DataRow
    'returns an array of DataRow objects representing the child view 
    For Each oChildRow In oDataRow.GetChildRows("SelfRefenceRelation")
        'Create child node and add to Parent
        Dim oChildNode As New TreeNode()
        oChildNode.Text = oChildRow(DataTextField).ToString()
        oChildNode.Value = oChildRow(DataFieldID).ToString()
        oChildNode.NavigateUrl = _
        'Repeat for each child
        RecursivelyLoadTree(oChildRow, oChildNode)
    Next oChildRow
End Sub 'RecursivelyLoadTree

Using the code

The easiest way to use the control is to either bind it to a Data Source control (DataSourceControl.aspx):

<%@ Register TagPrefix="CPArticles" Namespace="CPArticles"%>

<CPArticles:AutoBindingTree runat="server" ID="TestCtrl" 






  <asp:SqlDataSource id="SqlDataSource1" runat="server" 

    ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 

        SelectCommand="SELECT * FROM SelfReferenceTable" 



or by programmatically setting the DataSource property(DataBind.aspx):

TestCtrl.DataFieldID = "ID"
TestCtrl.DataFieldParentID = "ParentID"
TestCtrl.DataTextField = "Text"
TestCtrl.DataSource = oDs

Both samples and the SQL Script are in the demo application.


  • April 15, 2007: Initial release.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Bassam Saoud
Software Developer (Senior) Delcan Corporation
United States United States
Bassam Saoud is a software developer with more then 6+ years of experience. He has masters in Computer Science from American University of Technology and is currently doing Masters in Business Administration at Colorado Heights University. He started Programming with C++ and VB and now working with ASP.NET VB.NET/C#, SQL Server 2000/2005.

His interests are mainly politics, Basketball and Traveling.

You may also be interested in...


Comments and Discussions

QuestionOnSelectedNodeChanged Pin
kerm795-Apr-11 0:16
memberkerm795-Apr-11 0:16 
AnswerRe: OnSelectedNodeChanged Pin
ahussiny24-Mar-12 3:05
memberahussiny24-Mar-12 3:05 
GeneralIs there any way to save this to xml? [modified] Pin
Kaeghl29-Jan-09 7:25
memberKaeghl29-Jan-09 7:25 
GeneralGenerating Treeview from datatable Pin
amitabha200712-Jan-09 22:31
memberamitabha200712-Jan-09 22:31 
QuestionTreeView From Datatable Pin
amitabha200712-Jan-09 22:29
memberamitabha200712-Jan-09 22:29 
GeneralYou can achieve this with one line of code Pin
Ralph Varjabedian23-Apr-08 1:15
memberRalph Varjabedian23-Apr-08 1:15 
GeneralRe: You can achieve this with one line of code Pin
Bassam Saoud28-Jul-08 4:44
memberBassam Saoud28-Jul-08 4:44 
GeneralRe: You can achieve this with one line of code Pin
Ralph Varjabedian28-Jul-08 5:14
memberRalph Varjabedian28-Jul-08 5:14 
GeneralRe: You can achieve this with one line of code Pin
Bassam Saoud28-Jul-08 5:17
memberBassam Saoud28-Jul-08 5:17 
GeneralRe: You can achieve this with one line of code Pin
Ralph Varjabedian29-Jul-08 0:02
memberRalph Varjabedian29-Jul-08 0:02 
GeneralExcellent stuff Pin
geckex3-Feb-08 13:12
membergeckex3-Feb-08 13:12 
GeneralRe: Excellent stuff Pin
Bassam Saoud4-Feb-08 3:56
memberBassam Saoud4-Feb-08 3:56 
QuestionHow to extend a TreeView Control with this binding and what you've done in your other article? Pin
AnksuNico20-Nov-07 8:24
memberAnksuNico20-Nov-07 8:24 
AnswerRe: How to extend a TreeView Control with this binding and what you've done in your other article? Pin
Bassam Saoud20-Nov-07 8:33
memberBassam Saoud20-Nov-07 8:33 
GeneralI want to set First of all Root elements (ParentID = 0),how edit the code [modified] Pin
maseccc9-Sep-07 23:24
membermaseccc9-Sep-07 23:24 
GeneralRe: I want to set First of all Root elements (ParentID = 0),who to edit the code Pin
Bassam Saoud10-Sep-07 4:41
memberBassam Saoud10-Sep-07 4:41 
GeneralRe: I want to set First of all Root elements (ParentID = 0),who to edit the code [modified] Pin
maseccc10-Sep-07 16:21
membermaseccc10-Sep-07 16:21 
GeneralRe: I want to set First of all Root elements (ParentID = 0),who to edit the code [modified] Pin
AnksuNico20-Nov-07 6:33
memberAnksuNico20-Nov-07 6:33 
Questionsource code and database Pin
cedey5-Aug-07 19:14
membercedey5-Aug-07 19:14 
AnswerRe: source code and database Pin
Bassam Saoud6-Aug-07 1:13
memberBassam Saoud6-Aug-07 1:13 
GeneralCreate Tag "Target" Pin
Godinho Ferreira16-Apr-07 13:08
memberGodinho Ferreira16-Apr-07 13:08 
GeneralCreat Target Pin
Godinho Ferreira16-Apr-07 13:06
memberGodinho Ferreira16-Apr-07 13:06 
GeneralRe: Creat Target Pin
Jeff Circeo19-Apr-07 7:56
memberJeff Circeo19-Apr-07 7:56 
GeneralRe: Creat Target Pin
tomot15-Oct-07 1:22
membertomot15-Oct-07 1:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190306.1 | Last Updated 16 Apr 2007
Article Copyright 2007 by Bassam Saoud
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid