Tuesday, January 12, 2010

N Level TreeView

CatagoryID ParentCatagoryID

1 --

2 --

4 2

5 2

6 1

7 --

8 4

9 2


<asp:TreeView ID="TreeView1" runat="server" OnTreeNodePopulate="TreeView_TreeNodePopulate" />
    protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateRootLevel();
}
}

private void PopulateRootLevel()
{
SqlConnection objConn = new SqlConnection(ConnectionString);

SqlCommand objCommand = new SqlCommand("SELECT sc.CatagoryID, sc.ParentCatagoryID,(SELECT COUNT(*) FROM yourtable WHERE (ParentCatagoryID= sc.CategoryID)) AS childnodecount FROM yourtable AS sc", objConn);

SqlDataAdapter da = new SqlDataAdapter(objCommand);DataTable dt = new DataTable();

da.Fill(dt);

PopulateNodes(dt, TreeView1.Nodes);
}

private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
tn.Value = dr["CatagoryId"].ToString();
tn.Text = dr["CatagoryId"].ToString();
nodes.Add(tn);
//If node has child nodes, then enable on-demand populating
tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
}
}

protected void TreeView_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
int ParentCatagoryID= Int32.Parse(e.Node.Value);
PopulateSubLevel(ParentCatagoryID, e.Node);
}

private void PopulateSubLevel(int ParentCatagoryID, TreeNode parentNode)
{
//Your sublevel Datatable ie. dtSub
PopulateNodes(dtSub, parentNode.ChildNodes);
}


No comments:

Post a Comment