August 27, 2009 by Christoff Truter 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]
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
CREATE PROCEDURE viewMyTable AS BEGIN SELECT ID, title, ISNULL(parentID, 0) AS parentID FROM myTable END
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]
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);
}
}
}
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); } } } } }