Populate TreeView from Database using C#

June 13, 2013 // In: C#

load_treeview_from_database_sharpcodersTreeView Control is most important and useful control. Basically TreeView control allows you to display data in hierarchical form. In this tutorial, you will learn, how  TreeView Menu can be populated from databas. I’ll use User_Menu table to load data to TreeView.

 

 

 

User_Menu Structure

First of All you need to mapp User_Menu Database Table to C# DataTable, So that you can populate TreeView without intracting with database. We have created a method LoadDataTable that loads Data from Database Table to DataTable and returns DataTable.

Next Step is to create a method to load Data to TreeView. The logic is, you need to select Parent Records. For this purpose, set ParentId to 0, Parent records are such records  that have no parent. Now apply foreach loop on Master records and load its corresponding child one by one through recursion.

loadTreeMenu method is created to load Parent Nodes and loadTreeSubMenu method is created to load corresponding child nodes.

Parameters: 

  • TreeView placed on the form/Page
  • DataTable that is loaded from Database table

In loadTreeSubMenu recursion is used to load child nodes.

You can call method loadTreeMenu to load Menu to TreeView .

Thats It!!!

 

Validate TextBox For Digits, Alphabets, AlphaNumeric Characters
C# Coding Standards and Best Programming Practice Part-3