TreeView Navigation Control in VisualStudio2008
TreeView
TreeView an ASP.net control . It is there in the toolbox inside the “Navigation” tab.It is one among the very few navigation controls and comes in to use when we need nesting or recursion.
Pre-Requisites
- Drag and drop a TreeView Control “TreeView1″ in our Asp.Net webpage (Default2.aspx).
- Data to the control is bound from a table.Here I am using Ms-sqlserver.View table structure.
- A class is used for database connectivity “DBAccess.cs”.
After creating the page and adding the control , a few lines of code can simply fill the tree nodes. First step is to make an object of the “DBAccess” class,which is used to get database connectivity. The expanding icon “Arrow” (as in the picture) can be set by using a property of the treeview control ” ImageSet”.Now in the page load a method is called -”PopulateTreeView( )”.
“PopulateTreeView( ) method” :-
First step is to execute a select query using the object of the DBAccess class.Now the parent and child nodes of the tree are set using a loop.
Default2.aspx.cs(Code behind file of the web page)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
DBAccess dba = new DBAccess();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateTreeView();
}
}
public void PopulateTreeView()
{
dba.GetTable("select * from SampleTable");
foreach (DataRow dr in dba.dt.Rows)
{
TreeNode parentNode = new TreeNode((string)dr["PKey"]);
TreeView1.Nodes.Add(parentNode);
for (int i = 1; i < dba.dt.Columns.Count; i++)
{
TreeNode childNode = new TreeNode(dr.ItemArray[i].ToString());
parentNode.ChildNodes.Add(childNode);
}
}
}
}
DBAccess class
I am tired writing down the same code again and again…So you can get the code detail here or can read it at the end of this page.
TableName : SampleTable
Fields:
PKey varchar(50) Primary key of the table
FieldName varchar(50) A column
AnotherField varchar(50) A column
RowStatus int A column to indicate the status, by default it is 1.
OutPut Screenshot
Related posts:








Leave your response!