Introduction

TreeView control used to represent hierarchical data using expandable nodes. TreeView control is available in WinForms and WPF as well.

This article will guide you to “How to populate and add new nodes to TreeView up-to-N Levels from Database”. You will be able to add a new node at any level and expand this up-to-N Levels and generate automatic code for any child.

Description

First of all, create database table with the given model. We will use only one table, as we have to expand it to N level. I have used SQL Server 2014. Any version of sql server can be used.

  

 

SQL
Edit|Remove
CREATE TABLE [dbo].accounts( 
 
       [code] [intNOT NULL, 
 
       [ac_name] [nvarchar](50NOT NULL, 
 
       [parent] [intNOT NULL, 
 
       [type] [nvarchar](20NOT NULL, 
 
       [levelno] [intNOT NULL, 
 
       [fixed] [nvarchar](50NULL, 
 
       [direct] [nvarchar](50NULL, 
 
       [open_bal] [decimal](182NULL, 
 
       [dt] [datetimeNULL CONSTRAINT [DF_chart_dt]  DEFAULT (getdate()), 
 
       [active] [intNOT NULL CONSTRAINT [DF_chart_active]  DEFAULT ((1)), 
 
       [cntr] [intIDENTITY(1,1NOT NULL, 
 
 CONSTRAINT [PK_chartPRIMARY KEY CLUSTERED 
 
( 
 
       [codeASC 
 
)WITH (PAD_INDEX = OFFSTATISTICS_NORECOMPUTE = OFFIGNORE_DUP_KEY = OFFALLOW_ROW_LOCKS = ONALLOW_PAGE_LOCKS = ONON [PRIMARY] 
 
) ON [PRIMARY]

The field ‘code’ will be the primary key. It will use to identify each account. The program will automatically generate code for any new node.

Add some dummy data to this table
SQL
Edit|Remove
SETIDENTITY_INSERT [dbo].accountsONGOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (1N'Assets'0N'Parent Account'0N'NA'N'NA'CAST(0.00ASDecimal(182)), CAST(N'2015-02-23 21:09:27.327'ASDateTime), 11) 
 
GOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (2N'Liabilities'0N'Parent Account'0N'NA'N'NA'CAST(0.00ASDecimal(182)), CAST(N'2015-02-23 21:09:27.327'ASDateTime), 12) 
 
GOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (3N'Equity'0N'Parent Account'0N'NA'N'NA'CAST(0.00ASDecimal(182)), CAST(N'2015-02-23 21:09:27.327'ASDateTime), 13) 
 
GOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (4N'Revenue'0N'Parent Account'0N'Variable'N'Indirect'CAST(0.00ASDecimal(182)), CAST(N'2015-02-26 00:00:00.000'ASDateTime), 138) 
 
GOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (101N'Current Assets'1N'Parent Account'1N'NA'N'NA'CAST(0.00ASDecimal(182)), CAST(N'2015-02-23 21:09:27.327'ASDateTime), 14) 
 
GOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (102N'Fixed Assets'1N'Parent Account'1N'NA'N'NA'CAST(0.00ASDecimal(182)), CAST(N'2015-02-23 21:09:27.327'ASDateTime), 15) 
 
GOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (201N'Short Term Liabilities'2N'Parent Account'1N'NA'N'NA'CAST(0.00ASDecimal(182)), CAST(N'2015-02-23 21:09:27.327'ASDateTime), 16) 
 
GOINSERT [dbo].accounts ([code], [ac_name], [parent], [type], [levelno], [fixed], [direct], [open_bal], [dt], [active], [cntr]) VALUES (202N'Long Term Liabilities'2N'Parent Account'1N'NA'N'NA'CAST(0.00ASDecimal(182)), CAST(N'2015-02-23 21:09:27.327'ASDateTime), 17) 
 
GOSETIDENTITY_INSERT [dbo].accountsOFFGO

Populating the TreeView

After creating the table and adding data to it, now we are able to populate data into TreeView.

Follow the following steps.

Displaying Node Data

The following function is used to display details of a specific node.

C#
Edit|Remove
privatevoid ShowNodeData(TreeNode nod) { 
 
            DataRow r = _acountsTb.Rows[int.Parse(nod.Tag.ToString())]; 
 
            txtCode.Text = r["code"].ToString(); 
 
            txtName.Text = r["ac_name"].ToString(); 
 
            dtpDate.Value = DateTime.Parse(r["dt"].ToString()); 
 
            textBox1.Text = r["open_bal"].ToString(); 
 
 
            if (r["type"].ToString().Equals("Parent Account")) 
 
            { 
 
                radioParent.Checked = true; 
 
                textBox1.Enabled = false; 
 
            } 
 
            else 
 
                radioTransaction.Checked = true; 
 
            if (r["fixed"].ToString().Equals("NA")) 
 
                radioNA1.Checked = true; 
 
            elseif (r["fixed"].ToString().Equals("Fixed")) 
 
                radioFixed.Checked = true; 
 
            else 
 
                radioVariable.Checked = true; 
 
            if (r["direct"].ToString().Equals("NA")) 
 
                radioNA2.Checked = true; 
 
            elseif (r["direct"].ToString().Equals("Direct")) 
 
                radioDirect.Checked = true; 
 
            else 
 
                radioIndirect.Checked = true; 
 
            txtName.Focus();   
 
        }

Adding new node at this level

The following event handler handles the click action of context menu item “At this level”. This event first create code for the new item to be inserted.

C#
Edit|Remove
privatevoid atThisLevelToolStripMenuItem_Click(object sender, EventArgs e) 
 
        { 
 
            
 
            _selectedNode = treeView1.SelectedNode; 
 
            int max = 0; 
 
            if (treeView1.Nodes.Count > 0) 
 
            { 
 
                _parent = int.Parse(_acountsTb.Rows[int.Parse(_selectedNode.Tag.ToString())]["parent"].ToString()); 
 
                DataRow[] nodes = _acountsTb.Select("[parent]=" + _parent); 
 
 
                foreach (DataRow r in nodes) 
 
                { 
 
                    int n = int.Parse(r["code"].ToString()); 
 
                    if (n > max) 
 
                        max = n; 
 
 
                } 
 
            } 
 
            max += 1; 
 
            txtCode.Text = max.ToString(); 
 
            _newNode = true; 
 
            _thisLevel = true; 
 
            txtName.Focus(); 
 
        }

Adding new node under selected node

The following event handler handles the click action of context menu item “Under Select”. This event first create code for the new item to be inserted.

C#
Edit|Remove
private void underSelectedToolStripMenuItem_Click(object sender, EventArgs e) 
        { 
            _selectedNode = treeView1.SelectedNode; 
             
            DataRow r = _acountsTb.Rows[int.Parse(treeView1.SelectedNode.Tag.ToString())]; 
            if (r["type"].ToString().Equals("Parent Account")) 
            { 
                _newNode = true; 
                _thisLevel = false; 
                string code = string.Empty; 
                _parent = int.Parse(_acountsTb.Rows[int.Parse(_selectedNode.Tag.ToString())]["code"].ToString()); 
                 
                if (_selectedNode.Nodes.Count > 0) 
                { 
 
                    DataRow[] nodes = _acountsTb.Select("[parent]=" + _parent); 
                    int max = 0; 
                    foreach (DataRow ra in nodes) 
                    { 
                        int n = int.Parse(ra["code"].ToString()); 
                        if (n > max) 
                            max = n; 
 
                    } 
                    max += 1; 
                    txtCode.Text = max.ToString(); 
                    code = max.ToString(); 
                } 
                else 
                { 
                    if (_selectedNode.Level < 3) 
                        code = "01"; 
                    else 
                        code = "001"; 
 
                    txtCode.Text = r["code"] + code; 
                } 
                txtName.Focus(); 
 
            } 
            else 
            { 
                _newNode = false; 
                MessageBox.Show("New Account can't be opened under a Transaction Account""Acount opening Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 
        }
 

  

  

  

Source Code Files

Conclusion

The above tutorial shows you, how we can dynamically create and populate TreeView in C# up-to N Levels. We can generate code automatically at any level.