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,

Insert some hierarchal data.


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)


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

	SELECT ID, title, ISNULL(parentID, 0) AS parentID
	FROM myTable

Add a same table key contraint.

ALTER TABLE [dbo].[myTable]  WITH CHECK ADD  CONSTRAINT [FK_myTable_myTable] FOREIGN KEY([parentID])
REFERENCES [dbo].[myTable] ([ID])
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

November 1, 2010 by Alexey

Great works for MySQL! Thank you Christoff Truter! I using MySQL Connector .NET v6.3.2 and Visual Studio 2008 Express. ========================================================== MySQL table ------------------------ CREATE TABLE IF NOT EXISTS `strana` ( `id` int(10) unsigned NOT NULL auto_increment, `pid` int(10) NOT NULL default '0', `name` varchar(120) NOT NULL, PRIMARY KEY (`id`) ) TYPE=MyISAM DEFAULT CHARSET=cp1251; INSERT INTO `strana` (`id`, `pid`, `name`) VALUES (1, '0', 'Центральный Федеральный округ'), (2, '0', 'Северо-Западный Федеральный округ'), (3, '1', 'Белгородская область'), (4, '1', 'Брянская область'), (5, '2', 'Республика Карелия'), (6, '2', 'Республика Коми'), (7, '3', 'Алексеевка'), (8, '3', 'Белгород'), (9, '4', 'Брянск'), (10, '4', 'Дятьково'), (11, '5', 'Беломорск'), (12, '5', 'Кемь'), (13, '6', 'Воркута'), (14, '6', 'Вуктыл'); ========================================================== File dbconf.cfg -------------------------- server=localhost; user=root; database=country; port=3306; password=; ========================================================== C# code ------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using MySql.Data; using MySql.Data.MySqlClient; namespace country { public partial class Form1 : Form { MySqlDataAdapter Adapt; DataSet Dts; string config = "dbconf.cfg"; public Form1() { InitializeComponent(); try { // read dbconf.cfg StreamReader sr = File.OpenText(config); string conf = sr.ReadToEnd(); sr.Close(); // new connection for MySQL MySqlConnection conn = new MySqlConnection(conf); conn.Open(); DataTable dtTree = new DataTable(); string sql = "SELECT id, pid, name FROM strana"; Adapt = new MySqlDataAdapter(sql, conn); Adapt.Fill(dtTree); Adapt.Dispose(); treeView1.BeginUpdate(); treeView1.Nodes.Clear(); CreateTreeView(treeView1.Nodes, 0, dtTree); //treeView1.Nodes[0].Expand(); treeView1.Select(); treeView1.EndUpdate(); conn.Close(); } catch (FileNotFoundException fs) { textBox1.Text = "Error: File not found - " + fs.FileName; } catch (Exception ex) { textBox1.Text = ex.ToString(); } } // create tree protected void CreateTreeView(TreeNodeCollection parentNode, int parentID, DataTable mytab) { foreach (DataRow dta in mytab.Rows) { if (Convert.ToInt32(dta["pid"]) == parentID) { String key = dta["id"].ToString(); String text = dta["name"].ToString(); TreeNodeCollection newParentNode = parentNode.Add(key, text).Nodes; CreateTreeView(newParentNode, Convert.ToInt32(dta["id"]), mytab); } } } } }

July 8, 2010 by Anonymous

Thank you man .. I've been working on this for a while now and you just saved my time .. KISSES

car audio amplifier June 13, 2010 by http://www.amplifiercars.com

thank's this is work

June 3, 2010 by Christoff Truter

Glad you came right btw the code in this link is actually ASP.net based http://www.cstruter.com/blog/264

June 2, 2010 by newbie

I got it to work from this link: http://www.daniweb.com/forums/thread118395.html.

June 2, 2010 by newbie

I'm using asp.net. How do you implement the aspx side? Many tks again.

Alternative June 1, 2010 by Christoff Truter

Have a look at this link: http://www.cstruter.com/blog/264

June 1, 2010 by newbie

Compile ok with your suggestion, but I now have problem calling/referencing from aspx. Can you share your others (perhaps better) examples? Many tks again for sharing. I've been searching days for this.

May 29, 2010 by Christoff Truter

Hi there, in which Namespaces is your "TreeNodeCollection" - e.g. are you using the one from the ASP.net classes or the one for windows forms? In ASP.net you'd do something like this: TreeNode newNode = new TreeNode(text, key); parentNode.Add(newNode); I've got other (perhaps better) examples of how to achieve this though

May 29, 2010 by newbie

Compile error: "No overload for method 'Add' takes '2' argument for TreeNodeCollection newParentNode = parentNode.Add(key,text).Nodes; Help please!