Code to bind Telerik treeview

888 views Asked by At

I am New with Telerik tools, currently I have a task to bind 3 level hierarchical tree PARENT, CHILD, SUBCHILD. I have googled a lot and also visited Telerik demo site but that code is not working im my case.

Please provide code to bind Radtree. My table structure is :

**ID**    **ParentID**  **Descriptoin**

1           1   Live animals

2           1   Live horses, asses, mules and hinnies

3           2   Live pure-bred breeding animals

4           2   Other live hoses, asses, mules and hinnies
1

There are 1 answers

0
Ryno Coetzee On
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GenerateTreeView();
            }
        }

The method below will do a select from your table - creating a relation between ID (which I assume is the treeviews "MAIN PARENT" node) and the "Parent_ID" (which I assume is the child node). It will then create the parent node and subsequently for each child populate the parent node with the method RecursivelyPopulate

        private void GenerateTreeView()
        {
            SqlConnection con = new SqlConnection("CONN STR");
            con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM MY TABLE", con);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            ds.Relations.Add("NodeRelation", 
                             ds.Tables[0].Columns["ID"],
                             ds.Tables[0].Columns["ParentID"]);
            foreach (DataRow dbRow in ds.Tables[0].Rows)
            {
                if (dbRow.IsNull("PARENTID"))
                {
                    RadTreeNode node = CreateNode(dbRow["Description"].ToString(), true);
                    RadTreeView1.Nodes.Add(node);
                    RecursivelyPopulate(dbRow, node);
                }
            }
        }

The method below (RecursivelyPopulate) will for each child in the relation create a child node for the parent created in the method above (GenerateTreeView)

        private void RecursivelyPopulate(DataRow dbRow, RadTreeNode node)
        {
               foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
               {
                   RadTreeNode childNode = CreateNode(childRow["Description"].ToString();
                   node.Nodes.Add(childNode);
                   RecursivelyPopulate(childRow, childNode);
               }
        }

** Depending on your table structure you can have an Indefinite amount of Parent-Child relations by using the above code snippet