Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 622205
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T18:57:34+00:00 2026-05-13T18:57:34+00:00

Aloha, I’m trying to populate a treeview on a windows form app with Hierarchical

  • 0

Aloha,
I’m trying to populate a treeview on a windows form app with Hierarchical data from a SQL db.

The structure from the database is:

id_def  id_parent description
1     NULL      Multidificiência
2     NULL      Síndrome
3     NULL      Outros
4     1       Surdez de Transmissão
5     2       Surdez Neurossensorial Ligeira
6     3       Surdez Neurossensorial Média

the records with NULL value at id_parent, are the main categories, and the ones with their id_parent, are sub categories.

Can anyone help with the code to populate the TreeView ?
I managed to do it with an ASP.NET app, if it helps, here’s the code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        PopulateRootLevel();
}

private void PopulateRootLevel()
{
    SqlConnection objConn = new SqlConnection("Data Source=1.1.1.1;Initial Catalog=DREER_EDUCANDOS2006;User ID=sre_web;Password=xxx");
    SqlCommand objCommand = new SqlCommand("select id_deficiencia,descricao,(select count(*) FROM NecessidadesEspeciais WHERE id_deficiencia_pai=sc.id_deficiencia) childnodecount FROM NecessidadesEspeciais sc where id_deficiencia_pai IS NULL", objConn);
    SqlDataAdapter da = new SqlDataAdapter(objCommand);
    DataTable dt = new DataTable();
    da.Fill(dt);
    PopulateNodes(dt, TreeView1.Nodes);
}

private void PopulateSubLevel(int parentid, TreeNode parentNode)
{
    SqlConnection objConn = new SqlConnection("Data Source=1.1.1.1;Initial Catalog=DREER_EDUCANDOS2006;User ID=sre_web;Password=xxx");
    SqlCommand objCommand = new SqlCommand("select id_deficiencia,descricao,(select count(*) FROM NecessidadesEspeciais WHERE id_deficiencia_pai=sc.id_deficiencia) childnodecount FROM NecessidadesEspeciais sc where id_deficiencia_pai=@id_deficiencia_pai", objConn);
    objCommand.Parameters.Add("@id_deficiencia_pai", SqlDbType.Int).Value = parentid;
    SqlDataAdapter da = new SqlDataAdapter(objCommand);
    DataTable dt = new DataTable();
    da.Fill(dt);
    PopulateNodes(dt, parentNode.ChildNodes);
}


protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
    PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
}

private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
{
    foreach (DataRow dr in dt.Rows)
    {
        TreeNode tn = new TreeNode();
        tn.Text = dr["descricao"].ToString();
        tn.Value = dr["id_deficiencia"].ToString();
        nodes.Add(tn);

        //If node has child nodes, then enable on-demand populating
        tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T18:57:34+00:00Added an answer on May 13, 2026 at 6:57 pm

    Take a table with some hierarchical data in it:

    Id  Name                                ParentNodeId
    1   Top-level node 1                    -1
    2   A first-level child                  1
    3   Another top-level node              -1
    4   Another first-level child            1
    5   First-level child in another branch  3
    6   A second-level child                 2
    

    I have reworked the sample code from another SO answer, to use the above table to dynamically populate a tree view (assuming the table lives in an SQL server database). The code sample is somewhat lenghty…

    using System.Windows.Forms;
    using System.Threading;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    public class TreeViewSample : Form
    {
        private TreeView _treeView;
        public TreeViewSample()
        {
            this._treeView = new System.Windows.Forms.TreeView();
            this._treeView.Location = new System.Drawing.Point(12, 12);
            this._treeView.Size = new System.Drawing.Size(200, 400);
            this._treeView.AfterExpand +=
                new TreeViewEventHandler(TreeView_AfterExpand);
            this.ClientSize = new System.Drawing.Size(224, 424);
            this.Controls.Add(this._treeView);
            this.Text = "TreeView Lazy Load Sample";
            PopulateChildren(null);
        }
    
        void TreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Tag == "dummy")
            {
                PopulateChildren(e.Node);
            }
        }
    
        private void PopulateChildren(TreeNode parent)
        {
            // this node has not yet been populated, launch a thread
            // to get the data
            int? parentId = parent != null ? (parent.Tag as DataNode).Id : (int?)null;
            ThreadPool.QueueUserWorkItem(state =>
            {
                IEnumerable<DataNode> childItems = GetNodes(parentId);
                // load the data into the tree view (on the UI thread)
                _treeView.BeginInvoke((MethodInvoker)delegate
                {
                    PopulateChildren(parent, childItems);
                });
            });
        }
    
        private void PopulateChildren(TreeNode parent, IEnumerable<DataNode> childItems)
        {
            TreeNodeCollection nodes = parent != null ? parent.Nodes : _treeView.Nodes;
            TreeNode child;
            TreeNode dummy;
            TreeNode originalDummyItem = parent != null ? parent.Nodes[0] : null;
            foreach (var item in childItems)
            {
                child = new TreeNode(item.Text);
                child.Tag = item;
                dummy = new TreeNode("Loading. Please wait...");
                dummy.Tag = "dummy";
                child.Nodes.Add(dummy);
                nodes.Add(child);
            }
            if (originalDummyItem != null)
            {
                originalDummyItem.Remove();
            }
        }
    
        private IEnumerable<DataNode> GetNodes(int? parentId)
        {
            List<DataNode> result = new List<DataNode>();
            using (SqlConnection conn = new SqlConnection(@"[your connection string]"))
            using (SqlCommand cmd = new SqlCommand("select * from Nodes where ParentNodeId = @parentNodeId", conn))
            {
                cmd.Parameters.Add(new SqlParameter("@parentNodeId", System.Data.SqlDbType.Int));
                cmd.Parameters["@parentNodeId"].Value = parentId != null ? parentId : -1;
                conn.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    int nodeIdCol = reader.GetOrdinal("NodeId");
                    int nameCol = reader.GetOrdinal("Name");
                    int parentIdCl = reader.GetOrdinal("ParentNodeId");
                    while (reader.Read())
                    {
                        result.Add(new DataNode
                           {
                               Id = reader.GetInt32(nodeIdCol),
                               Text = reader.GetString(nameCol),
                               ParentId = reader.IsDBNull(parentIdCl) ? (int?)null : reader.GetInt32(parentIdCl)
                           });
                    }
                }
            }
            return result;
        }
    }
    
    public class DataNode
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public int? ParentId { get; set; }
    }
    

    The data fetching code can probably be made a bit prettier by using Linq-to-SQL, but I wanted the same to be as complete as possible, so I decided to leave that out to keep the amount of code down… (that would require the inclusion of some generated Linq-to-SQL classes).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Aloha I have a VS2008 solution to which I want to add a webservice
Aloha I have a method with (pseudo) signature: public static T Parse<T>(string datadictionary) where
Aloha I received a nice wsdl with xs: documentation tags like: <xs:complexType name=Supplier> <xs:annotation>
Aloha I'm referencing an external webservice in my .NET 2.0 application. Adding a service
I'm trying to alpha blend sprites and backgrounds with devkitPro (including libnds, libarm, etc).
I have an HBITMAP containing alpha channel data. I can successfully render this using
Aloha, I'm looking for a floating div type of control, to display another (user)control
Aloha, I have a 8MB XML file that I wish to deserialize. I'm using
Aloha Given a plug-in architecture (C# / .NET 3.5) with the plug-ins stored in
Aloha I received a few nice xsd files which I want to convert to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.