Populate a TreeView Control 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:









Comments



good one


Add Images to treenode

Its good, But how can i add images to childnodes


Thanks.... brother

It helps me.... >:D<


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', '&#1062;&#1077;&#1085;&#1090;&#1088;&#1072;&#1083;&#1100;&#1085;&#1099;&#1081; &#1060;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1099;&#1081; &#1086;&#1082;&#1088;&#1091;&#1075;'), (2, '0', '&#1057;&#1077;&#1074;&#1077;&#1088;&#1086;-&#1047;&#1072;&#1087;&#1072;&#1076;&#1085;&#1099;&#1081; &#1060;&#1077;&#1076;&#1077;&#1088;&#1072;&#1083;&#1100;&#1085;&#1099;&#1081; &#1086;&#1082;&#1088;&#1091;&#1075;'), (3, '1', '&#1041;&#1077;&#1083;&#1075;&#1086;&#1088;&#1086;&#1076;&#1089;&#1082;&#1072;&#1103; &#1086;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;'), (4, '1', '&#1041;&#1088;&#1103;&#1085;&#1089;&#1082;&#1072;&#1103; &#1086;&#1073;&#1083;&#1072;&#1089;&#1090;&#1100;'), (5, '2', '&#1056;&#1077;&#1089;&#1087;&#1091;&#1073;&#1083;&#1080;&#1082;&#1072; &#1050;&#1072;&#1088;&#1077;&#1083;&#1080;&#1103;'), (6, '2', '&#1056;&#1077;&#1089;&#1087;&#1091;&#1073;&#1083;&#1080;&#1082;&#1072; &#1050;&#1086;&#1084;&#1080;'), (7, '3', '&#1040;&#1083;&#1077;&#1082;&#1089;&#1077;&#1077;&#1074;&#1082;&#1072;'), (8, '3', '&#1041;&#1077;&#1083;&#1075;&#1086;&#1088;&#1086;&#1076;'), (9, '4', '&#1041;&#1088;&#1103;&#1085;&#1089;&#1082;'), (10, '4', '&#1044;&#1103;&#1090;&#1100;&#1082;&#1086;&#1074;&#1086;'), (11, '5', '&#1041;&#1077;&#1083;&#1086;&#1084;&#1086;&#1088;&#1089;&#1082;'), (12, '5', '&#1050;&#1077;&#1084;&#1100;'), (13, '6', '&#1042;&#1086;&#1088;&#1082;&#1091;&#1090;&#1072;'), (14, '6', '&#1042;&#1091;&#1082;&#1090;&#1099;&#1083;'); ========================================================== 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); } } } } }


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


car audio amplifier

thank's this is work


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


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


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


Alternative

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


1 2 Last / 2 Pages (16 Entries)

Post comment

Name *
Email
Title
Body *
Security Code
*
* Required fields

Related Posts

Latest Posts

Be the best stalker you can be


2011-12-13 22:33:54

Syntactic sugar (C#): Enum


2011-08-04 16:50:18

Top 5 posts

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51