TreeView Part 1 - Populating the New TreeView Control from a Hierarchical Database Table - Step 2 - Populating the Data
(Page 3 of 4 )
Open your code behind file. I will be using C# in this tutorial, but you should have no trouble converting the code to VB.Net if you need to. First let’s reference the proper namespaces, and create a DataSet to hold the data.
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
DataSet EmployeeDS = new DataSet();
Now, we need to configure the page to pull the data on first load, dump it into the DataSet, then into the TreeView. The best way to accomplish this is by separating out the data pull and tree population into two separate methods. The two primary reasons for this are:
The method for populating the TreeView is recursive. We only need to hit the database once, so we would have to build expensive conditional logic into the recursive method for that to happen. It’s easiest to create a separate function to pull the data and only call it once.
If there is an error in either step, it’s far easier to isolate if we have separate, distinct functions to debug.
So here’s the code to do this on the first page load:
void page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// first load DataSet
LoadDataSet();
// now build list
BuildEmployeeList(EmployeeList.Nodes, 0);
}
}
Now here’s the code to load the DataSet. It’s pretty basic stuff, so I won’t go into any deep explanation. Just to explain, I’m assuming that you’re storing your connection string in the web.config file as is the best practice, and that’s where the ‘conn’ variable is reading from.
void LoadDataSet()
{
String conn =
ConfigurationSettings.AppSettings["connStr"];
String strSQL =
"SELECT id, name, mgr_id FROM [employees]";
SqlDataAdapter myAdapter =
new SqlDataAdapter(strSQL, conn);
myAdapter.Fill(EmployeeDS, "employees");
}
So now we have all the necessary employee data in the DataSet. You can feel free to modify that step all you need to, build in whatever error handling logic and connection closing steps you’d like. Now we’ll get into the recursive function to populate the tree.
Next: Step 3 - Building the Tree >>
More Database Articles
More By Justin Cook