Click here to Skip to main content
15,883,705 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to load the  following table in the form of a treeview in my C# WPF Application. This is my table : Drinks
DrinksId     DrinksName   Level1  Level2   Level3   Level4   Level5
  1           Drinks         0      0        0        0         0
  2           Cold           1      0        0        0         0
  3           Pepsi          1      1        0        0         0
  4           Light          1      1        1        0         0
  5           Zero           1      1        2        0         0
  6           Heavy          1      1        3        0         0
  7           Cola           1      2        0        0         0
  8           Zero           1      2        1        0         0
  9           Light          1      2        2        0         0
  10          One-Light      1      2        2        1         0
  11          Two-Light      1      2        2        2         0
  12          7-UP           1      3        0        0         0
  13          Hot            2      0        0        0         0
  14          Coffee         2      1        0        0         0
  15          Black          2      1        1        0         0
  16          Espresso       2      1        2        0         0
  
 My treeview should be like this:-
      Drinks
      |----Cold
      |--------Pepsi
      |------------Light
      |------------Zero
      |------------Heavy
      |--------Cola
      |------------Zero
      |------------Light
      |----------------One-Light
      |----------------Two-Light
      |--------7-Up
      |------Hot
      |---------Coffee
      |--------------Black
      |--------------Espresso
      
I tried with Hierarchical data template to display the levels  in my XAML. I tried binding my treeview to the Observable Collection, as I need to add, remove, update items later. 
Now nothing is getting displayed. I don't know where I am going wrong. Please Help


What I have tried:

HTML
<pre><Window.Resources>
        <DataTemplate x:Key="level5">
            <TextBlock Text="{Binding DrinkName}"/>
        </DataTemplate>
        <HierarchicalDataTemplate x:Key="level4" ItemTemplate="{StaticResource level5}">
            <TextBlock Text="{Binding DrinkName}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate x:Key="level3" ItemTemplate="{StaticResource level4}">
            <TextBlock Text="{Binding DrinkName}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate x:Key="level2" ItemTemplate="{StaticResource level3}">
            <TextBlock Text="{Binding DrinkName}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate x:Key="level1"  ItemTemplate="{StaticResource level2}">
            <TextBlock Text="{Binding DrinkName}"/>
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Grid>
        <TreeView Name="treeviewdrinks" ItemsSource="{Binding Mytv,UpdateSourceTrigger=PropertyChanged}" />
    </Grid>

C#
<pre>public MainWindow()
        {
            InitializeComponent();
            LoadTreeView();
        }
        private void LoadTreeView()
        {
                string connectionString = @"Provider=SQLOLEDB.1; Data Source=PBA-PC\SQLEXPRESS; Initial Catalog = DemoDB; Integrated Security=SSPI;";
                OleDbConnection oledbconn = new OleDbConnection(connectionString);
                oledbconn.Open();
                OleDbDataAdapter oleda = new OleDbDataAdapter();
                Mytv = new ObservableCollection<treeviewcollection>();
                treeviewdrinks.DataContext = Mytv;
                try
                {

                    OleDbCommand olecmd = new OleDbCommand("Select * from Drinks Where Level1 <> 0 and Level2 = 0 and Level3 = 0 and Level4 = 0 and Level5 = 0", oledbconn);
                    DataSet ds = new DataSet();
                    //ds.Relations.Add()
                    oleda.SelectCommand = olecmd;
                    oleda.Fill(ds);
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        Mytv.Add(new treeviewcollection { DrinkName = dr["DrinkName"].ToString() });
                        var step1 = "";
                        OleDbCommand olecmd1 = new OleDbCommand("SELECT * From Drinks Where Level1 = ? and Level2 <> 0 and Level3 = 0 and Level4 = 0 and Level5 = 0", oledbconn);
                        // MessageBox.Show(dr["Level1"].ToString());
                        olecmd1.Parameters.AddWithValue(@step1, dr["Level1"].ToString());
                        OleDbDataAdapter oleda1 = new OleDbDataAdapter(olecmd1);
                        DataSet ds1 = new DataSet();
                        oleda1.Fill(ds1);
                        foreach (DataRow dr1 in ds1.Tables[0].Rows)
                        {
                            Mytv.Add(new treeviewcollection { DrinkName = dr1["DrinkName"].ToString() });
                            var step2 = "";
                            OleDbCommand olecmd2 = new OleDbCommand("SELECT * From Drinks Where Level1 = ? and Level2 = ? and Level3 <> 0 and Level4 = 0 and Level5 = 0", oledbconn);
                            olecmd2.Parameters.AddWithValue(@step1, dr["Level1"].ToString());
                            olecmd2.Parameters.AddWithValue(@step2, dr1["Level2"].ToString());
                            OleDbDataAdapter oleda2 = new OleDbDataAdapter(olecmd2);
                            DataSet ds2 = new DataSet();
                            oleda2.Fill(ds2);
                            foreach (DataRow dr2 in ds2.Tables[0].Rows)
                            {
                                Mytv.Add(new treeviewcollection { DrinkName = dr2["DrinkName"].ToString() });
                                var step3 = "";
                                OleDbCommand olecmd3 = new OleDbCommand("SELECT * From Drinks Where Level1 = ? and Level2 = ? and Level3 = ? and Level4  <> 0 and Level5 = 0", oledbconn);
                                olecmd3.Parameters.AddWithValue(@step1, dr["Level1"].ToString());
                                olecmd3.Parameters.AddWithValue(@step2, dr1["Level2"].ToString());
                                olecmd3.Parameters.AddWithValue(@step3, dr2["Level3"].ToString());
                                OleDbDataAdapter oleda3 = new OleDbDataAdapter(olecmd3);
                                DataSet ds3 = new DataSet();
                                oleda3.Fill(ds3);
                                foreach (DataRow dr3 in ds3.Tables[0].Rows)
                                {
                                    Mytv.Add(new treeviewcollection { DrinkName = dr3["DrinkName"].ToString() });
                                    var step4 = "";
                                    OleDbCommand olecmd4 = new OleDbCommand("SELECT  * From Drinks Where Level1 = ? and Level2 = ? and Level3 = ? and Level4 = ? and Level5  <> 0", oledbconn);
                                    olecmd4.Parameters.AddWithValue(@step1, dr["Level1"].ToString());
                                    olecmd4.Parameters.AddWithValue(@step2, dr1["Level2"].ToString());
                                    olecmd4.Parameters.AddWithValue(@step3, dr2["Level3"].ToString());
                                    olecmd4.Parameters.AddWithValue(@step4, dr3["Level4"].ToString());
                                    OleDbDataAdapter oleda4 = new OleDbDataAdapter(olecmd4);
                                    DataSet ds4 = new DataSet();
                                    oleda4.Fill(ds4);
                                    foreach (DataRow dr4 in ds4.Tables[0].Rows)
                                    {
                                        Mytv.Add(new treeviewcollection { DrinkName = dr4["DrinkName"].ToString() });

                                    }
                                }
                            }
                        }
                    }

                } // End try

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {

                    oledbconn.Close();
                }
        }
        private ObservableCollection<treeviewcollection> _mytv;
        public ObservableCollection<treeviewcollection> Mytv
        {
            get { return _mytv; }
            set
            {
                _mytv = value;
                OnPropertyChanged("Mytv");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public class treeviewcollection
        {

            public string DrinkName { get; set; }


        }
          public class level5 
           {

               public string DrinkName { get; set; }


           }
           public class level4
           { 
               public string DrinkName { get; set; }
               ObservableCollection<level5> l4;
           }
           public class level3
           {

               public string DrinkName { get; set; }
               ObservableCollection<level4> l3;

           }
           public class level2 
           {
              public string DrinkName { get; set; }
              ObservableCollection<level3> l2;
           }
           public class level1
           { 
               public string DrinkName { get; set; }
               ObservableCollection<level2> l1;
           }


    }
Posted
Updated 13-Jun-19 8:51am
Comments
Graeme_Grant 8-Jun-19 23:56pm    
I've seen this exact question been asked here before about the same time as last year, so it appears to be an assignment for a class that you're doing ...

We are not here to debug your code for you ...

What is your question?
Priya Karthish 9-Jun-19 17:15pm    
It's me , who posted the question 2 months before. I am working with a similar database in my work(This one I worked as a Sample). I was able to display my treeview without adding Hierarchical datatemplate and Observable Collection. Now since I want my Treeview to perform lot of actions, I need it to be done with Observable Collection. I tried adding ObservableCollection, but nothing is displayed in the Output Window. I tried my level best to find out where I am going wrong. But I couldn't find it out. If possible, please help me with the issue.
Priya Karthish 11-Jun-19 13:41pm    
Could someone help me with the issue?
George Swan 14-Jun-19 1:17am    
A great demo on how to use a TreeView is available on Codeproject at https://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

1 solution

Overall your business models should be organized by business rules, and the whole concept of "level" is creating database models based on the view which is problematic for several reasons.

You should have something like:

DrinkCategory
Drink
DrinkVariety

Where a DrinkCategory can have a collection of subcategories along with a collection of Drinks, a Drink has a collection of DrinkVariety objects, and the DrinkVariety can have a collection of subvarieties. That way you can have a HierarchialTemplate specific to the three model objects rather than having to do anything funky.

Outside of the model issues, the reason why it's not working as you expect is two-fold: 1) your HierarchialDataTemplates do not declare their ItemsSource; 2) your templates are keyed and not defaulted by datatype. You've got the item templates referenced for everything but level 1 though, so you could workaround #2 if you just specify the "level1" template for the ItemTemplate in the TreeView.
 
Share this answer
 
Comments
Priya Karthish 28-Jun-19 10:06am    
This is a sample database. Actual database which I work consists of heterogenous data with almost 5 levels. After specifying the datatype and adding Itemssource, still nothing is getting displayed. Please suggest me a tutorial with heterogeneous data and also loading from database, which will help me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900