Tuesday, December 20, 2011

Bind DataBase Data to TreeView


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.Data.SqlClient;

public partial class Treeview : System.Web.UI.Page
{
    SqlConnection cn = new SqlConnection("server=.;database=Prasad;uid=sa;pwd=sa123");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            filldata();
        }
    }

    private void filldata()
    {
        try
        {
            cn.Open();
            {
                SqlCommand SqlCmd = new SqlCommand("Select id,NodeName from tblTreeViewParent", cn);
                SqlDataReader Sdr = SqlCmd.ExecuteReader();
                SqlCmd.Dispose();
                string[,] ParentNode = new string[100, 2];
                int count = 0;

                while (Sdr.Read())
                {
                    ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("id")).ToString();
                    ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("NodeName")).ToString();
                }
                Sdr.Close();
                for (int loop = 0; loop < count; loop++)
                {
                    TreeNode root = new TreeNode();
                    root.Text = ParentNode[loop, 1];
                    //root.Target = "_blank";
                    //root.NavigateUrl = "Tree1.aspx";

                    SqlCommand Module_SqlCmd = new SqlCommand("Select id , ChieldName from tblTreeviewChild where Pid =" + ParentNode[loop, 0], cn);
                    SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();
                    while (Module_Sdr.Read())
                    {
                        //siva To Add children module to the root node
                        TreeNode child = new TreeNode();
                        child.Value = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("id")).ToString();
                        child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChieldName")).ToString();
                        //child.Target = "_blank";
                        //child.NavigateUrl = "Tree2.aspx";
                        root.ChildNodes.Add(child);
                    }
                    Module_Sdr.Close();
                    TreeView1.Nodes.Add(root);
                    TreeView1.ExpandAll();

                }

            }

        }
        catch
        {
        }
        finally
        {
            cn.Close();
        }
    }
}

No comments:

Post a Comment