Click here to Skip to main content
15,887,267 members
Articles / Treeview
Article

Dynamically Binding Values to TreeView Control

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL1 min read 9K   1   1
First Create Two Tables ParentTable and ChildTableParentTable-->ParentId as Primary Key-->ParentNameChildTable -->ParentId as FOREIGN KEY

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

First Create Two Tables ParentTable and ChildTable

ParentTable

-->ParentId as Primary Key

-->ParentName

ChildTable

-->ParentId as FOREIGN KEY from ParentTable

-->ChildName

-----------------------------------------------------------------------

Create Url SqlConnection...

Then Use This Function to fill TreeView Control


public void fill_Tree()
{
        try
        {
            TreeView1.Nodes.Clear();
            if (con.State == ConnectionState.Closed)
                con.Open();

            SqlCommand SqlCmd = new SqlCommand("Select * from ParentTable", con);
            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("ParentID")).ToString();
                ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("ParentName")).ToString();
            }

            Sdr.Close();


            for (int loop = 0; loop < count; loop++)
            {
                TreeNode root = new TreeNode();

                root.Text = ParentNode[loop, 1];
                root.Target = "_blank";
                root.NavigateUrl = "ParentPage.aspx?NodeName=" + root.Text + "";


                SqlCommand Module_SqlCmd = new SqlCommand("Select * from ChildTable where ParentId =" + ParentNode[loop, 0], con);
                SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();

                while (Module_Sdr.Read())
                {
                    TreeNode child = new TreeNode();

                    child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString();
                    child.Target = "_blank";
                    child.NavigateUrl = "ChildPage.aspx?NodeName=" + child.Text + "";

                    root.ChildNodes.Add(child);
                }

                Module_Sdr.Close();

                TreeView1.Nodes.Add(root);
            }


            TreeView1.ExpandAll();
            con.Close();
        }
        catch (Exception ex)
        {
            this.ErrorState = true;
            this.ErrorMsg = ex.Message;
        }
}

protected void Page_Load(object sender, EventArgs e)
{
        if (!IsPostBack == true)
        {
            fill_Tree();
        }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
QuestionHow to bind Treeview dynamically Pin
Vivek VIshwas10-Nov-17 1:12
Vivek VIshwas10-Nov-17 1:12 
here is my code Please check and resolve..

<div>
<asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
VerticalPadding="0px" />
</asp:TreeView>
</div>

//.cs---------------
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT cid,cname FROM TopParent");
this.PopulateTreeView(dt, 0, null);
}
}

private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
{
foreach (DataRow row in dtParent.Rows)
{
TreeNode child = new TreeNode
{
Text = row["cName"].ToString(),
Value = row["cId"].ToString()
};
if (parentId == 0)
{
TreeView1.Nodes.Add(child);
DataTable dtChild = this.GetData("SELECT cname,cid FROM TopParent WHERE PId = " + child.Value);
PopulateTreeView(dtChild, int.Parse(child.Value), child);
}
else
{
treeNode.ChildNodes.Add(child);
}
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}



here is my Table ------
Id PId PName Cid CName
1 NULL NULL 10 India
2 10 India 1010 Delhi
3 10 India 1011 UP
4 10 India 1012 MP
5 10 India 1013 Haryana
6 1010 Delhi 101010 Laxmi Nagar
9 1011 UP 101110 Vaishali
11 1012 MP 101210 Satna
12 1013 Haryana 101310 Rewari
7 1010 Delhi 101011 Preet Vihar
8 1010 Delhi 101012 Anand Vihar
10 1011 UP 101111 Ghaziabad


Now My Tree view is being binding successfully. But It is repeating sub nodes in bottom please check and update me.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.