-->

Thursday, June 6, 2013

How to bind TreeView with database table in c# Windows Form

How to bind TreeView with database table in c# Windows Form

TreeView displays a hierarchical collection of labelled items to the user that optionally contains an image. Microsoft is also using treeview in left side of windows explorer from the time of windows 98 till now.



It is very simple to add a root node with some child nodes to treeview as:
TreeView with database
Now in this article I am going to bind this treeview through a database table having following properties:
TreeView with database
Create a database having single table i.e. TreeNode1 as I have described in my previous post “How to create database using Entity Framework”. To bind treeview to table there should be some records in our table Treenode1, so let add some entries to database like:

TreeView with database
Now to bind treeview with table TreeNode1 write following code in our Form1’s constructor
TreeView with database
Here in the first statement I got all the records which have Parent key = 0 i.e. they will be our root node. Now one by one we will check if any node in database have this node as its parent node, if any, then create that new node to its child node.
At the last add that root node to treeview and that is it. I have a screenshot also as an example.
TreeView with database
Download source code.

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved