Home » ASP.Net, Tech Corner

TreeView Navigation Control in VisualStudio2008

5 June 2009 No Comments Posted By:LG

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

screenshot_treeview_3tt.jpg

Related posts:

  1. Filling a DataGridView-Windows Controls
  2. DataBase Access in dot net
  3. F# -New Programming Language from Microsoft

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>