Populate a TreeView Control C#

August 27, 2009 by C#  

Populating a TreeView control in a windows application using SQL and C# is quite straightforward.

Create a self referencing table, lets call it myTable, quite orginal don't you think? ;)

CREATE TABLE [dbo].[myTable](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[title] [varchar](255) NOT NULL,
	[parentID] [int] NULL,
 CONSTRAINT [PK_myTable] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Insert some hierarchal data.

SET IDENTITY_INSERT myTable ON
GO

INSERT INTO myTable(ID, title, parentID) VALUES(1,'Microsoft', NULL)
INSERT INTO myTable(ID, title, parentID) VALUES(2,'C#', 1)
INSERT INTO myTable(ID, title, parentID) VALUES(3,'VB.net', 1)
INSERT INTO myTable(ID, title, parentID) VALUES(4,'Open Source', NULL)
INSERT INTO myTable(ID, title, parentID) VALUES(5,'Python',	4)
INSERT INTO myTable(ID, title, parentID) VALUES(6,'Ruby', 4)
INSERT INTO myTable(ID, title, parentID) VALUES(7,'PHP', 4)
INSERT INTO myTable(ID, title, parentID) VALUES(8,'Perl', 4)
INSERT INTO myTable(ID, title, parentID) VALUES(9,'Java', 4)
INSERT INTO myTable(ID, title, parentID) VALUES(10,'LinQ', 2)
INSERT INTO myTable(ID, title, parentID) VALUES(11,'5.2', 7)
INSERT INTO myTable(ID, title, parentID) VALUES(12,'4.4', 7)

GO
SET IDENTITY_INSERT myTable OFF
GO

I assume in my code example that the root parent node equals 0, hence when returning results from SQL like in the stored procedure, I use the ISNULL method to return 0 from a NULL.

You can just define a root value as well...

CREATE PROCEDURE viewMyTable
AS
BEGIN
	SELECT ID, title, ISNULL(parentID, 0) AS parentID
	FROM myTable
END

Add a same table key contraint.

ALTER TABLE [dbo].[myTable]  WITH CHECK ADD  CONSTRAINT [FK_myTable_myTable] FOREIGN KEY([parentID])
REFERENCES [dbo].[myTable] ([ID])
GO
ALTER TABLE [dbo].[myTable] CHECK CONSTRAINT [FK_myTable_myTable]


  • In your windows application, drag and drop a treeview control onto your form.
  • Populate a DataTable with your stored procedure.
Pass your TreeNodeCollection, the parentID you wish to start with and DataTable to the following method: eg. PopulateTreeView(SomeTreeView.Nodes, 0, SomeDataTable);

protected void PopulateTreeView (TreeNodeCollection parentNode, int parentID, DataTable folders)
{   
    foreach (DataRow folder in folders.Rows)
    {
        if (Convert.ToInt32(folder["parentID"]) == parentID)
        {
            String key = folder["ID"].ToString();
            String text = folder["title"].ToString();
            TreeNodeCollection newParentNode = parentNode.Add(key, text).Nodes;
            PopulateTreeView(newParentNode, Convert.ToInt32(folder["ID"]), folders);                    
        }
    }
}

If everything went according to plan, you'll end up with something like this:

Leave a Comment


tnx April 15, 2016 by Sohrab

thanks for your solution. I attempt to use recursive for this problem,but I could not. Your answer Is Perfect.

Treeview August 28, 2015 by devidas

Good Example

thank you ! June 20, 2014 by Anonymous

thank you !

Thank you May 11, 2014 by Ali

your code is very useful for me. thanks a lot thank you man. your are my hero

problems June 11, 2013 by alex

i'm doing exactly like you and the result was the next: An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll how can I fixe it?

سپاس May 17, 2013 by dvdj

سلام دو روز تو اینترنت دنبالش میگشتم!! سپاسگذارم private void button1_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); TreeNodeCollection parentNode = treeView1.Nodes; sqlDataAdapter dap = new sqlDataAdapter ("SELECT * FROM MyTable ", conn); dap.Fill(dt); PopulateTreeView(parentNode, 0, dt); }

April 21, 2013 by Anonymous

Thank you!!!!

thanks..... March 15, 2013 by Thành Trần

Good

Wow Fantastic ! February 9, 2013 by Dipu

Thanks dude..... U save me....

August 31, 2012 by firdaus.mansuri@gmail.com

coooooool


Related Posts

ASP.net(C#) Custom Hierarchical Datasource

April 11, 2010


Latest Posts

Dependency Injection using Ninject and PostSharp

April 26, 2016

Aspect Orientated Programming (AOP) - A Brief look at PostSharp

April 15, 2016

How to become a better programmer.

April 5, 2016

JavaScript Fundamentals - Hoisting

March 22, 2016

Quick and dirty look at ECMAScript 6

March 17, 2016

JavaScript Promises

March 9, 2016

CSS Combinators

March 7, 2016

Shingles Awareness

March 4, 2016

Google Analytics : Measurement Protocol

February 24, 2016

Interesting JavaScript - SQLite (sql.js)

February 18, 2016


Most Commented on Posts

Moving items between listboxes in ASP.net/PHP example

Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
June 12, 2008

Simple WYSIWYG Editor

Creating a WYSIWYG textbox for your website is actually quite simple.
February 1, 2007

C# YouTube : Google API

Post on how to integrate with YouTube using the Google Data API
March 12, 2011

Populate a TreeView Control C#

Populate a TreeView control in a windows application.
August 27, 2009

ASP.NET(C#) : Autocomplete TextBox - Part 1 (From Scratch)

Part one of how to create an autocomplete textbox using ASP.NET(C#)
March 27, 2011


Angular   Architecture   ASP.NET   Astronomy   Breaking News   C#   C++   Coding Horrors   Comedy   Cross Browser   CSS   Design Patterns   ES6   Google API   IIS   Integration   JavaScript   Jquery Mobile   Love and War   Microsoft Office   Ninject   Personal   PHP   PostSharp   SEO   South Africa   SQL   Threading   TypeScript   Visual Basic   XML