using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using System.Data;
using System.Data.SqlClient;



public partial class TelerikWebForm : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSide);
          
        }
    }

    private void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
    {
        DataTable data = GetData(new SqlCommand("SELECT * FROM ProductCategories WHERE ParentId IS NULL"));

        foreach (DataRow row in data.Rows)
        {
            RadTreeNode node = new RadTreeNode();
            node.Text = row["Title"].ToString();
            node.Value = row["CategoryId"].ToString();
            node.ExpandMode = expandMode;
            treeView.Nodes.Add(node);
        }
    }
    private static DataTable GetData(SqlCommand selectCommand)
    {
        selectCommand.Connection = new SqlConnection(
            ConfigurationManager.ConnectionStrings["TelerikConnectionString"].ConnectionString);
        SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);

        DataTable data = new DataTable();
        adapter.Fill(data);

        return data;
    }
    protected void RadTreeView_NodeExpand(object sender, RadTreeNodeEventArgs e)
    {
        if (e.Node.Nodes.Count == 0)
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSide);
    }

    private static DataTable GetChildNodes(string parentId)
    {
        SqlCommand selectCommand =
            new SqlCommand(
                @"
    SELECT
        pc1.CategoryID,
        pc1.Title,
        ISNULL(pc2.ChildrenCount, 0) as ChildrenCount
    FROM ProductCategories as pc1
    LEFT JOIN
        (
            SELECT ParentId, COUNT(*) AS ChildrenCount
            FROM ProductCategories
            Group By (ParentId)
        ) as pc2
    ON
        pc1.CategoryId = pc2.ParentId
    WHERE pc1.parentId = @parentId
");

        selectCommand.Parameters.AddWithValue("parentId", parentId);
        return GetData(selectCommand);
    }
    private static void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
    {
        DataTable data = GetChildNodes(e.Node.Value);

        foreach (DataRow row in data.Rows)
        {
            RadTreeNode node = new RadTreeNode();
            node.Text = row["Title"].ToString();
            node.Value = row["CategoryId"].ToString();
            if (Convert.ToInt32(row["ChildrenCount"]) > 0)
            {
                node.ExpandMode = expandMode;
            }
            e.Node.Nodes.Add(node);
        }

        e.Node.Expanded = true;
    }
}
