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 7841797
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T16:10:31+00:00 2026-06-02T16:10:31+00:00

thanks for taking the time out to read this post. I’m having trouble trying

  • 0

thanks for taking the time out to read this post.

I’m having trouble trying to build a hierarchial object when getting data from my SQL database.
Please note that I am a little bit of a newbie programmer.

How do you build a hierarchial object that has unknown levels? When I say unknown levels I mean, each node may have varying numbers of child nodes, which in turn may have varying numbers of its own child nodes, so on and so on.

The idea is that I need to create a hierarchial object using my SQL data to bind to WPF TreeView control.

Below I have included the code I have so far.
The first bit of code is my Class made up of Properties. Note that the “Products” class has an ObservableCollection referencing itself. I think this is how you construct the nested nodes. i.e. a list inside a list.

The second piece of code is my Get Method to download the data from the SQL database. Here is where I need to some how sort the downloaded data into a hierarchy.

Products Class (properties)

public class Products : INotifyPropertyChanged, IDataErrorInfo
{
    private Int64 m_ID;
    private SqlHierarchyId m_Hierarchy;
    private string m_Name;
    private ObservableCollection<Products> m_ChildProducts;

    // Default Constructor
    public Products()
    {
        ChildProducts = new ObservableCollection<Products>();
    }

    //Properties

    public Int64 ID
    {
        get
        {
            return m_ID;
        }
        set
        {
            m_ID = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ID"));
        }
    }

    public SqlHierarchyId Hierarchy
    {
        get
        {
            return m_Hierarchy;
        }
        set
        {
            m_Hierarchy = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Hierarchy"));
        }
    }

    public String Name
    {
        get
        {
            return m_Name;
        }
        set
        {
            m_Name = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Name"));
        }
    }

    public Int16 Level
    {
        get
        {
            return m_Level;
        }
        set
        {
            m_Level = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Level"));
        }
    }

    public Int64 ParentID
    {
        get
        {
            return m_ParentID;
        }
        set
        {
            m_ParentID = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ParentID"));
        }
    }

    public ObservableCollection<Products> ChildProducts
    {
        get
        {
            return m_ChildProducts;
        }
        set
        {
            m_ChildProducts = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ChildProducts"));
        }
    }

    //INotifyPropertyChanged Event
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, e);
    }
}

Method which gets data from SQL DB:

public static ObservableCollection<Products> GetProductsHierarchy()
    {

        ObservableCollection<Products> productsHierarchy = new ObservableCollection<Products>();

        SqlConnection connection = new SqlConnection(DBConnection.GetConnection().ConnectionString);

        string selectStatement = "SELECT ID, Hierarchy, Name, Hierarchy.GetLevel() AS Level, Hierarchy.GetAncestor(1) AS ParentHierarchy, " +
                                                 "(SELECT ID " +
                                                 "FROM SpecProducts " +
                                                 "WHERE (Hierarchy = SpecProducts_1.Hierarchy.GetAncestor(1))) AS ParentID " +
                                 "FROM  SpecProducts AS SpecProducts_1 " +
                                 "WHERE (EnableDisable IS NULL) " +
                                 "ORDER BY Hierarchy";

        SqlCommand selectCommand = new SqlCommand(selectStatement, connection);

        try
        {
            connection.Open();
            SqlDataReader reader = selectCommand.ExecuteReader();

            while (reader.Read())
            {

                Products product = new Products();
                product.ID = (Int64)reader["ID"];
                product.Name = reader["Name"].ToString();
                product.Hierarchy = (SqlHierarchyId)reader["Hierarchy"];
                product.Level = (Int16)reader["Level"];
                if (reader["ParentID"] != DBNull.Value)
                {
                    product.ParentID = (Int64)reader["ParentID"];
                }
                else
                {
                    product.ParentID = 0;
                }

                productsHierarchy.Add(product);

                // *** HOW TO BUILD HIERARCHY OBJECT WITH UNKNOWN & VARYING LEVELS?
                // *** ADD PRODUCT TO CHILDPRODUCT
            }

            return productsHierarchy;
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }
    }

Below I have attached an image showing the structure of my SQL Query Data.
Please note that the hierarchy level may go deeper when more products are added in the future. The Hierarchy object I need to create should be flexible enough to expand no matter what the number of node levels are.

Thank you very much for your time, all help is greatly appreciated.

SQL Query Data

********* EDIT 26/04/2012 14:37 *******************

Please find below a link to download my project code (this only contains treeview code).
Can someone please take a look at it to see why I cannot create nodes beyond 2 levels?

The code was given to me by user HB MAAM. Thank you “HB MAAM” for your help so far!

Click this link to download code

  • 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-06-02T16:10:37+00:00Added an answer on June 2, 2026 at 4:10 pm

    I will create an example for you,
    1- first i will create a class that holds the data that comes from the DB

    public class SqlDataDto
    {
        public int? Id { get; set; }
        public int? ParentId { get; set; }
    
        public String Name { get; set; }
        public String OtherDataRelatedToTheNode { get; set; }
    }
    

    2- that data will be converted to hierarchal data and we will use this class to hold it:

    public class LocalData : INotifyPropertyChanged
    {
        private int? _id;
        public int? Id
        {
            get { return _id; }
            set { _id = value; OnPropertyChanged("Id"); }
        }
    
        private int? _parentId;
        public int? ParentId
        {
            get { return _parentId; }
            set { _parentId = value; OnPropertyChanged("ParentId"); }
        }
    
        private string _name;
        public String Name
        {
            get { return _name; }
            set { _name = value; OnPropertyChanged("Name"); }
        }
    
        private string _otherDataRelatedToTheNode;
        public String OtherDataRelatedToTheNode
        {
            get { return _otherDataRelatedToTheNode; }
            set { _otherDataRelatedToTheNode = value; OnPropertyChanged("OtherDataRelatedToTheNode"); }
        }
    
        private LocalData _parent;
        public LocalData Parent
        {
            get { return _parent; }
            set { _parent = value; OnPropertyChanged("Parent"); }
        }
    
        private ObservableCollection<LocalData> _children;
        public ObservableCollection<LocalData> Children
        {
            get { return _children; }
            set { _children = value; OnPropertyChanged("Children"); }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
            }
        }
    }     
    

    3- finally we need to change the sql data to hierarchical one:

    public List<LocalData> GetHerachy(List<SqlDataDto> sqlData)
    {
        var sqlParents = sqlData.Where(q => q.ParentId == null).ToList();
        var parents = sqlParents.Select(q => new LocalData {Id = q.Id, Name = q.Name}).ToList();
        foreach (var parent in parents)
        {
            var childs = sqlData.Where(q => q.ParentId == parent.Id).Select(q => new LocalData { Id = q.Id, Name = q.Name , Parent = parent});
            parent.Children = new ObservableCollection<LocalData>(childs);
        }
        return parents;
    }
    

    4- then you can create a dummy data and convert it and show it in the tree:

    var sqlData = new List<SqlDataDto>
                      {
                          new SqlDataDto {Id = 1, ParentId = null, Name = "F1"}
                          , new SqlDataDto {Id = 2, ParentId = null, Name = "F2"}
                          , new SqlDataDto {Id = 3, ParentId = 1, Name = "S1"}
                          , new SqlDataDto {Id = 4, ParentId = 2, Name = "S21"}
                          , new SqlDataDto {Id = 5, ParentId = 2, Name = "S22"}
                      };
    treeView.ItemsSource = GetHerachy(sqlData);
    

    5- the tree should be like:

    <TreeView Name="treeView">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Children}">
                <TextBlock Text="{Binding Name}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Thanks for taking the time to read this. I have an unknown number of
Thanks everyone for taking the time to read this. I have styled my navigation
First, thanks in advance for taking the time to read through this. I have
Thanks for taking time to read this question. I am designing a 3-tier solution
Thanks for taking some time to help me out. Using: Microsoft Visual C# 2010
First of all thanks for taking the time to look into this. I store
Thanks for taking the time to help out. I'm using ASP.NET WebForms and I
Apologies if this is a repeat; I'm having a hard time figuring out what
Thank you for taking the time to read this and I will appreciate every
thanks for taking the time to stop by my question. Below you will find

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.