Friday 8 August 2014

Populate TreeView using recursion in ASP.Net

Populate TreeView using recursion in ASP.Net

In this article I will explain how to populate (bind) TreeView control with Nodes having Parent Child relationship from database in ASP.Net using C#.
The TreeView will be populated using recursion.
 
 Database
In order to populate TreeView with Parent Child relationship, I have made use of two tables namely VehicleTypes and VehicleSubTypes. The schema and the data present in both the tables are as follows.
VehicleTypes
 
HTML Page:
<h3>
    Vehicle Details</h3>
<hr />
<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>
C# Page:protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = this.GetData("SELECT Id, Name FROM VehicleTypes");
        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["Name"].ToString(),
            Value = row["Id"].ToString()
        };
        if (parentId == 0)
        {
            TreeView1.Nodes.Add(child);
            DataTable dtChild = this.GetData("SELECT Id, Name FROM VehicleSubTypes WHERE VehicleTypeId = " + 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;
    }
}

No comments:

Post a Comment