none
WPF- Treeview--How to add child nodes-- a Bizzare problem-- plz help

    Question

  • so here it is.... in WPF ... Treeview control --

    i can add nodes under root node, using XAML code  which is static

    i hav to add the nodes, using C# code which is dynamic. For Example: Menu Table

    MenuId       Name       ParentId
        1           Country         0
        2           India             1
        3           USA              1
        4           AP                2
        5           UP                2
        6           California      3
        7           Newyork       3


    In my C# Code i took a class file in that, i declared the menu() method of type DataTable.

    Method menu() :- I created a temptable (using DATATABLE CLASS) with same fields(using CLONE()) and filled it with MENU table data and returned that temptable.

    So now i have data with me.
    Based on ParentID i can retrieve the child values.

    but how to add those values to TREEVIEW as its ITEMS
    There is no---> " treeview1.Items[0].Items.Add() " thing in WPF--- n its creating problem to me.

    Hw can i do dat...? i dnt knw which Methods , Properties , Classes  to Use.
    Ex:
          + COUNTRY
                + INDIA
                       AP
                       UP
                 +USA
                       Lusiana
                       Nwyrk


    Please help.
    Thank you.

    Beginner in WPF..... VENU.
    Beginner in WPF.......VENU
    Saturday, May 16, 2009 1:02 PM

Answers

  • Hello Mr.Venu
    
    It is 3 level tree view
    
    Here I am giving the example for adding nodes for WPF tree view. Here we can also add image for the node,
    
    I am also sending SqlScript. 
    
    Run that script and fill tables with data
    
    XAML Code:
    
    
    <Window x:Class="sarath.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="408" Loaded="Window_Loaded">
        <Grid Width="356">
            <Label Margin="0,150,10,0" Height="28" HorizontalAlignment="Right" Name="lblselecteditem" VerticalAlignment="Top" Width="120">selected</Label>
    
            <Label Name="Location" FontWeight="bold"/>
            <ScrollViewer HorizontalScrollBarVisibility="auto" VerticalScrollBarVisibility="hidden" Name="scrollViewer">
    
                <TreeView Name="myTreeView" SelectedItemChanged="myTreeView_SelectedItemChanged" Margin="0,0,134,0" BorderThickness="0">
    
    
                </TreeView>
            </ScrollViewer>
    
        </Grid>
    </Window>
    
    Code Behind
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
    
    
    
    namespace sarath
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
                   
            public Window1()
            {
                InitializeComponent();
                 
                // Here we will Create the Dataset
                DataSet ds = new DataSet();
                
                // Here we will Create the SqlConnection
                SqlConnection con = new SqlConnection("");
    
                 // Here we will get the data from database by writing the stored procedure   
                SqlDataAdapter adapter = new SqlDataAdapter("sp_SelectTreeview", con);
                adapter.Fill(ds);
    
    
                List<MyMenuItem> myList = new List<MyMenuItem>();
    
                if (ds.Tables[0].Rows.Count > 0)
                {
    
                    for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                    {
                        myList.Add(new MyMenuItem(Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString()),
                                                  ds.Tables[0].Rows[i][1].ToString(), 0,0));
                                
                     
                        for (int j = 0; j <= ds.Tables[1].Rows.Count - 1; j++)
                        {
                            if (ds.Tables[0].Rows[i][0].ToString() == ds.Tables[1].Rows[j][1].ToString())
                            {
                                myList.Add(new MyMenuItem(Convert.ToInt32(ds.Tables[1].Rows[j][0].ToString()), 
                                ds.Tables[1].Rows[j][2].ToString(), Convert.ToInt32 (ds.Tables[0].Rows[i][0].ToString()),         
                                1));                                                     
                                
    
                                for (int k = 0; k <= ds.Tables[2].Rows.Count - 1; k++)
                                {
                                    if (ds.Tables[1].Rows[j][0].ToString() == ds.Tables[2].Rows[k][1].ToString())
                                    {
                                        
                                        myList.Add(new MyMenuItem(Convert.ToInt32(ds.Tables[2].Rows[k][0].ToString()),
                                        ds.Tables[2].Rows[k][2].ToString(),       
                                        Convert.ToInt32(ds.Tables[1].Rows[j][0].ToString()) ,2));     
                                    }
    
                                }
                            }
                        }
    
                    }
                }
    
                List<Image> imgList = new List<Image>();
                //Image img = Image.f
                 
                Dictionary<int, TreeViewItem> flattenedTree = new Dictionary<int, TreeViewItem>();
                        
                    foreach (MyMenuItem item in myList)
                    {
                        //TreeViewItem treeNode = new TreeViewItem();
                        //treeNode.Header = item.Header;
                        //treeNode.Tag = item;
    
                        TreeViewWithIcons node = new TreeViewWithIcons();
                        node.HeaderText = item.Header;
                        node.Tag = item;
                       
                                                                
                        flattenedTree.Add(item.ID, node);
    
                        // You have to place your required images in application folder
    
                        if (flattenedTree.ContainsKey(item.ParentID))
                        {
    
                            int l = item.LevelID;
    
                            if (item.LevelID == 1)
                            {
                               
                                 
                                // Here you have to give the image path 
                                string Path = @"";
                                node.Icon = CreateImage(Path);
                                flattenedTree[item.ParentID].Items.Add(node);
    
                            }
                            else if (item.LevelID == 2)
                            {
                                // Here you have to give the image path 
                                string Path = @"";
                                node.Icon = CreateImage(Path);
                                flattenedTree[item.ParentID].Items.Add(node);
                            }
                           
    
                        }
                        else
                        {
                            // Here you have to give the image path
                            string Path = @"";
                            node.Icon = CreateImage(Path);
                            myTreeView.Items.Add(node);
                        }                   
                    }  
                
            }
            private void myTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
            {
                TreeViewItem selectedTVI = (TreeViewItem)myTreeView.SelectedItem; 
    
                // To Get The value of Selected TvItem:
                string str = Convert.ToString(selectedTVI);
                noorbakshtree.MyMenuItem tvit;      //tvit variable of type MenuItem in this namespace:
                tvit =(MyMenuItem)selectedTVI.Tag;
                lblselecteditem.Content = Convert.ToString(tvit.ID);
            }
    
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
    
            }
    
            public BitmapImage CreateImage(string path)
            {
                BitmapImage myBitmapImage = new BitmapImage();
                myBitmapImage.BeginInit();
                myBitmapImage.UriSource = new Uri(path);
                myBitmapImage.EndInit();
                return myBitmapImage;
            }
        }
    
        class MyMenuItem
        {
            
            internal int ID
            { private set; get; }
    
            internal string Header
            { private set; get; }
    
            internal int ParentID
            { private set; get; }
    
            internal int LevelID
            { private set; get; }
    
            internal MyMenuItem(int id, string header, int parentId,int levelId)
            {
                ID = id;
                Header = header;
                ParentID = parentId;
                LevelID = levelId;
            }
        }
    
     }
    
    
    /// <summary>
    /// This Class Provides the TreeView with extended functionalities like,
    /// Adding the HeaderText feature to Node, Setting the icon for TreeViewNode.
    /// </summary>
    public class TreeViewWithIcons : TreeViewItem
    {
        #region Global variables
        ImageSource iconSource;
        TextBlock textBlock;
        Image icon;
        #endregion Global variables
    
        #region Constructors and Destructors
    
        public TreeViewWithIcons()
        {
            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;
            Header = stack;
            //Uncomment this code If you want to add an Image after the Node-HeaderText
            //textBlock = new TextBlock();
            //textBlock.VerticalAlignment = VerticalAlignment.Center;
            //stack.Children.Add(textBlock);
            icon = new Image();
            icon.VerticalAlignment = VerticalAlignment.Center;
            icon.Margin = new Thickness(0, 0, 4, 0);
            icon.Source = iconSource;
            stack.Children.Add(icon);
            //Add the HeaderText After Adding the icon
            textBlock = new TextBlock();
            textBlock.VerticalAlignment = VerticalAlignment.Center;
            stack.Children.Add(textBlock);
    
        }
    
        #endregion Constructors and Destructors
    
        #region Properties
    
        /// <summary>
        /// Gets/Sets the Selected Image for a TreeViewNode
        /// </summary>
        public ImageSource Icon
        {
            set
            {
                iconSource = value;
                icon.Source = iconSource;
            }
    
            get
            {
                return iconSource;
            }
    
        }
    
        #endregion Properties
    
        #region Event Handlers
    
        /// <summary>
        /// Event Handler on UnSelected Event
        /// </summary>
        /// <param name="args">Eventargs</param>
        protected override void OnUnselected(RoutedEventArgs args)
        {
            base.OnUnselected(args);
            icon.Source = iconSource;
    
        }
        /// <summary>
        /// Event Handler on Selected Event 
        /// </summary>
        /// <param name="args">Eventargs</param>
        protected override void OnSelected(RoutedEventArgs args)
        {
            base.OnSelected(args);
            icon.Source = iconSource;
        }
    
        /// <summary>
        /// Gets/Sets the HeaderText of TreeViewWithIcons
        /// </summary>
        public string HeaderText
        {
            set
            {
                textBlock.Text = value;
            }
            get
            {
                return textBlock.Text;
            }
        }
    
    
        #endregion Event Handlers
    
    }
    
    
    SqlScript:
    
    USE [TreeView]
    GO
    /****** Object:  Table [dbo].[tblCountry]    Script Date: 05/27/2009 10:56:55 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[tblCountry](
    	[CountryId] [bigint] IDENTITY(100,1) NOT NULL,
    	[GameId] [bigint] NOT NULL,
    	[CountryName] [nvarchar](50) NOT NULL,
    	[Description] [nvarchar](100) NULL,
     CONSTRAINT [PK_tblCountry] PRIMARY KEY CLUSTERED 
    (
    	[CountryId] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    /****** Object:  Table [dbo].[tblPlayer]    Script Date: 05/27/2009 10:56:57 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[tblPlayer](
    	[PlayerId] [bigint] IDENTITY(500,1) NOT NULL,
    	[CountryId] [bigint] NOT NULL,
    	[PlayerName] [nvarchar](50) NOT NULL,
    	[Description] [nvarchar](100) NULL,
     CONSTRAINT [PK_tblPlayer] PRIMARY KEY CLUSTERED 
    (
    	[PlayerId] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    /****** Object:  Table [dbo].[tblGame]    Script Date: 05/27/2009 10:56:56 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[tblGame](
    	[GameId] [bigint] IDENTITY(1,1) NOT NULL,
    	[GameName] [nvarchar](50) NOT NULL,
    	[Description] [nvarchar](100) NULL,
     CONSTRAINT [PK_tblGame] PRIMARY KEY CLUSTERED 
    (
    	[GameId] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    /****** Object:  StoredProcedure [dbo].[sp_SelectTreeview]    Script Date: 05/27/2009 10:56:54 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author:		<Sarath Chandra>
    -- Create date: <Create Date,,>
    -- Description:	<Description,,>
    -- =============================================
    CREATE PROCEDURE [dbo].[sp_SelectTreeview] 
    AS
    BEGIN
    	Select GameId,GameName from TblGame 
        Select CountryId,GameId,CountryName from TblCountry
        Select * from TblPlayer
    END
    GO
    
    
    • Marked as answer by Vvg585 Wednesday, May 27, 2009 5:39 AM
    Wednesday, May 27, 2009 5:34 AM
  • Hi Venu Volla,
    I do the  same in my code. It might not be the best way, but it works, so here it is:

    I have a Dictionary<int, TreeViewItem> called myDictionary which hold the MenuId as a int so I can get the correct TreeViewItem by just doing a myDictionay[anyMenuId].
    This will allow you to access the TreeViewItems by their MenuId and once you have it, you can add children to it. The rest will fall into place by TreeViewItems parent/child behavior.

    Of course you have to build the Dictionary from what you have.

    Hope this helps.

    noorbakhsh
    • Proposed as answer by noorbakhsh Monday, May 18, 2009 6:02 PM
    • Edited by noorbakhsh Monday, May 18, 2009 6:06 PM
    • Marked as answer by Tao Liang Wednesday, May 20, 2009 5:14 AM
    Monday, May 18, 2009 6:02 PM
  • Hi Venu Volla,

    Here is a simplified example of your code that runs exactly the way you want:

    In xaml:

    <Grid>
    <TreeView Name="myTreeView" />
    </Grid>


    In code:

    public partial class Window11 : Window
    {
    public Window11()
    {
    InitializeComponent();

    //I created my objects here, since I have no DataTable
    //It is assumed the the Parents appear before any child
    List<MyMenuItem> myList = new List<MyMenuItem>();
    myList.Add(new MyMenuItem(1, "Country", 0));
    myList.Add(new MyMenuItem(2, "U.S.A.", 1));
    myList.Add(new MyMenuItem(3, "India", 1));
    myList.Add(new MyMenuItem(4, "AP", 3));
    myList.Add(new MyMenuItem(5, "UP", 3));
    myList.Add(new MyMenuItem(6, "CA", 2));
    myList.Add(new MyMenuItem(7, "NY", 2));


    Dictionary<int, TreeViewItem> flattenedTree = new Dictionary<int, TreeViewItem>();


    foreach (MyMenuItem item in myList)
    {
    TreeViewItem treeNode = new TreeViewItem();
    treeNode.Header = item.Header;
    treeNode.Tag = item;
    flattenedTree.Add(item.ID, treeNode);


    if (flattenedTree.ContainsKey(item.ParentID))
    {
    flattenedTree[item.ParentID].Items.Add(treeNode);
    }
    else
    {
    myTreeView.Items.Add(treeNode);
    }
    }
    }
    }

    class MyMenuItem
    {
    internal int ID
    {private set;get;}

    internal string Header
    { private set; get; }

    internal int ParentID
    { private set; get; }

    internal MyMenuItem(int id, string header, int parentId)
    {
    ID = id;
    Header = header;
    ParentID = parentId;
    }
    }

    Hope this gets you going.


    noorbakhsh
    • Proposed as answer by noorbakhsh Wednesday, May 20, 2009 4:52 PM
    • Marked as answer by Vvg585 Thursday, May 21, 2009 11:00 AM
    Wednesday, May 20, 2009 4:51 PM

All replies

  • Hi Venu Volla,
    I do the  same in my code. It might not be the best way, but it works, so here it is:

    I have a Dictionary<int, TreeViewItem> called myDictionary which hold the MenuId as a int so I can get the correct TreeViewItem by just doing a myDictionay[anyMenuId].
    This will allow you to access the TreeViewItems by their MenuId and once you have it, you can add children to it. The rest will fall into place by TreeViewItems parent/child behavior.

    Of course you have to build the Dictionary from what you have.

    Hope this helps.

    noorbakhsh
    • Proposed as answer by noorbakhsh Monday, May 18, 2009 6:02 PM
    • Edited by noorbakhsh Monday, May 18, 2009 6:06 PM
    • Marked as answer by Tao Liang Wednesday, May 20, 2009 5:14 AM
    Monday, May 18, 2009 6:02 PM
  • hi Noorbakhsh,
    Im very happy to see your response, Thank you.

    still i have some problem with the solution you provided...

    1.How to create the Dictionary
    2.How to add items to Treeview from Dictionary

    can you be more eloberate... if possible..:)

    Thank you,
    Venu.
    Beginner in WPF.......VENU
    Wednesday, May 20, 2009 6:18 AM
  • Hi Venu Volla,

    Here is a simplified example of your code that runs exactly the way you want:

    In xaml:

    <Grid>
    <TreeView Name="myTreeView" />
    </Grid>


    In code:

    public partial class Window11 : Window
    {
    public Window11()
    {
    InitializeComponent();

    //I created my objects here, since I have no DataTable
    //It is assumed the the Parents appear before any child
    List<MyMenuItem> myList = new List<MyMenuItem>();
    myList.Add(new MyMenuItem(1, "Country", 0));
    myList.Add(new MyMenuItem(2, "U.S.A.", 1));
    myList.Add(new MyMenuItem(3, "India", 1));
    myList.Add(new MyMenuItem(4, "AP", 3));
    myList.Add(new MyMenuItem(5, "UP", 3));
    myList.Add(new MyMenuItem(6, "CA", 2));
    myList.Add(new MyMenuItem(7, "NY", 2));


    Dictionary<int, TreeViewItem> flattenedTree = new Dictionary<int, TreeViewItem>();


    foreach (MyMenuItem item in myList)
    {
    TreeViewItem treeNode = new TreeViewItem();
    treeNode.Header = item.Header;
    treeNode.Tag = item;
    flattenedTree.Add(item.ID, treeNode);


    if (flattenedTree.ContainsKey(item.ParentID))
    {
    flattenedTree[item.ParentID].Items.Add(treeNode);
    }
    else
    {
    myTreeView.Items.Add(treeNode);
    }
    }
    }
    }

    class MyMenuItem
    {
    internal int ID
    {private set;get;}

    internal string Header
    { private set; get; }

    internal int ParentID
    { private set; get; }

    internal MyMenuItem(int id, string header, int parentId)
    {
    ID = id;
    Header = header;
    ParentID = parentId;
    }
    }

    Hope this gets you going.


    noorbakhsh
    • Proposed as answer by noorbakhsh Wednesday, May 20, 2009 4:52 PM
    • Marked as answer by Vvg585 Thursday, May 21, 2009 11:00 AM
    Wednesday, May 20, 2009 4:51 PM
  • Bunches n Bunches of Thanks to you Noorbaksh....:)

    Your reply is really helpful to us.

    Yup..!! it really get me going much ahead of my requirements..... Thank you once again...

    If i have any more issues i wil post them..n i really appreciate your support....:)


    Beginner in WPF.......VENU
    Thursday, May 21, 2009 11:05 AM
  • Hi Noor...,

    Im again stucked at another problem...n in need ur help
    see i have prepared a collection of images, in the same way i prepared a collection of my nodes...

    But,

    Now, How to bind these IMAGES along with the NODES.... to TREEVIEW.

    I have to present lik this....
     
    +(image)Country
             +(image)USA
                        (imgae)NY
                        (image)CN

    For instance... assume i have this image and a node

    Image img1 = new Image();
                img1.Width = 20;
                img1.Margin = new Thickness(2);
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.UriSource = new Uri(@"/Images/City.png", UriKind.RelativeOrAbsolute);
                bi.EndInit();
                img1.Source = bi;

    now hw cn i show lik this  +(image)Country  

    im not going to use the image control r any xaml code... i need to do this throug Code behind only....

    Thank you for your help
    venu


    Beginner in WPF.......VENU
    Monday, May 25, 2009 8:37 AM
  • Venu Volla,
    Please see http://www.c-sharpcorner.com/UploadFile/mahesh/WPFTreeView08202008231544PM/WPFTreeView.aspx

    hope it helps.
    noorbakhsh
    Tuesday, May 26, 2009 4:28 PM
  • Hello Mr.Venu
    
    It is 3 level tree view
    
    Here I am giving the example for adding nodes for WPF tree view. Here we can also add image for the node,
    
    I am also sending SqlScript. 
    
    Run that script and fill tables with data
    
    XAML Code:
    
    
    <Window x:Class="sarath.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="408" Loaded="Window_Loaded">
        <Grid Width="356">
            <Label Margin="0,150,10,0" Height="28" HorizontalAlignment="Right" Name="lblselecteditem" VerticalAlignment="Top" Width="120">selected</Label>
    
            <Label Name="Location" FontWeight="bold"/>
            <ScrollViewer HorizontalScrollBarVisibility="auto" VerticalScrollBarVisibility="hidden" Name="scrollViewer">
    
                <TreeView Name="myTreeView" SelectedItemChanged="myTreeView_SelectedItemChanged" Margin="0,0,134,0" BorderThickness="0">
    
    
                </TreeView>
            </ScrollViewer>
    
        </Grid>
    </Window>
    
    Code Behind
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
    
    
    
    namespace sarath
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
                   
            public Window1()
            {
                InitializeComponent();
                 
                // Here we will Create the Dataset
                DataSet ds = new DataSet();
                
                // Here we will Create the SqlConnection
                SqlConnection con = new SqlConnection("");
    
                 // Here we will get the data from database by writing the stored procedure   
                SqlDataAdapter adapter = new SqlDataAdapter("sp_SelectTreeview", con);
                adapter.Fill(ds);
    
    
                List<MyMenuItem> myList = new List<MyMenuItem>();
    
                if (ds.Tables[0].Rows.Count > 0)
                {
    
                    for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                    {
                        myList.Add(new MyMenuItem(Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString()),
                                                  ds.Tables[0].Rows[i][1].ToString(), 0,0));
                                
                     
                        for (int j = 0; j <= ds.Tables[1].Rows.Count - 1; j++)
                        {
                            if (ds.Tables[0].Rows[i][0].ToString() == ds.Tables[1].Rows[j][1].ToString())
                            {
                                myList.Add(new MyMenuItem(Convert.ToInt32(ds.Tables[1].Rows[j][0].ToString()), 
                                ds.Tables[1].Rows[j][2].ToString(), Convert.ToInt32 (ds.Tables[0].Rows[i][0].ToString()),         
                                1));                                                     
                                
    
                                for (int k = 0; k <= ds.Tables[2].Rows.Count - 1; k++)
                                {
                                    if (ds.Tables[1].Rows[j][0].ToString() == ds.Tables[2].Rows[k][1].ToString())
                                    {
                                        
                                        myList.Add(new MyMenuItem(Convert.ToInt32(ds.Tables[2].Rows[k][0].ToString()),
                                        ds.Tables[2].Rows[k][2].ToString(),       
                                        Convert.ToInt32(ds.Tables[1].Rows[j][0].ToString()) ,2));     
                                    }
    
                                }
                            }
                        }
    
                    }
                }
    
                List<Image> imgList = new List<Image>();
                //Image img = Image.f
                 
                Dictionary<int, TreeViewItem> flattenedTree = new Dictionary<int, TreeViewItem>();
                        
                    foreach (MyMenuItem item in myList)
                    {
                        //TreeViewItem treeNode = new TreeViewItem();
                        //treeNode.Header = item.Header;
                        //treeNode.Tag = item;
    
                        TreeViewWithIcons node = new TreeViewWithIcons();
                        node.HeaderText = item.Header;
                        node.Tag = item;
                       
                                                                
                        flattenedTree.Add(item.ID, node);
    
                        // You have to place your required images in application folder
    
                        if (flattenedTree.ContainsKey(item.ParentID))
                        {
    
                            int l = item.LevelID;
    
                            if (item.LevelID == 1)
                            {
                               
                                 
                                // Here you have to give the image path 
                                string Path = @"";
                                node.Icon = CreateImage(Path);
                                flattenedTree[item.ParentID].Items.Add(node);
    
                            }
                            else if (item.LevelID == 2)
                            {
                                // Here you have to give the image path 
                                string Path = @"";
                                node.Icon = CreateImage(Path);
                                flattenedTree[item.ParentID].Items.Add(node);
                            }
                           
    
                        }
                        else
                        {
                            // Here you have to give the image path
                            string Path = @"";
                            node.Icon = CreateImage(Path);
                            myTreeView.Items.Add(node);
                        }                   
                    }  
                
            }
            private void myTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
            {
                TreeViewItem selectedTVI = (TreeViewItem)myTreeView.SelectedItem; 
    
                // To Get The value of Selected TvItem:
                string str = Convert.ToString(selectedTVI);
                noorbakshtree.MyMenuItem tvit;      //tvit variable of type MenuItem in this namespace:
                tvit =(MyMenuItem)selectedTVI.Tag;
                lblselecteditem.Content = Convert.ToString(tvit.ID);
            }
    
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
    
            }
    
            public BitmapImage CreateImage(string path)
            {
                BitmapImage myBitmapImage = new BitmapImage();
                myBitmapImage.BeginInit();
                myBitmapImage.UriSource = new Uri(path);
                myBitmapImage.EndInit();
                return myBitmapImage;
            }
        }
    
        class MyMenuItem
        {
            
            internal int ID
            { private set; get; }
    
            internal string Header
            { private set; get; }
    
            internal int ParentID
            { private set; get; }
    
            internal int LevelID
            { private set; get; }
    
            internal MyMenuItem(int id, string header, int parentId,int levelId)
            {
                ID = id;
                Header = header;
                ParentID = parentId;
                LevelID = levelId;
            }
        }
    
     }
    
    
    /// <summary>
    /// This Class Provides the TreeView with extended functionalities like,
    /// Adding the HeaderText feature to Node, Setting the icon for TreeViewNode.
    /// </summary>
    public class TreeViewWithIcons : TreeViewItem
    {
        #region Global variables
        ImageSource iconSource;
        TextBlock textBlock;
        Image icon;
        #endregion Global variables
    
        #region Constructors and Destructors
    
        public TreeViewWithIcons()
        {
            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;
            Header = stack;
            //Uncomment this code If you want to add an Image after the Node-HeaderText
            //textBlock = new TextBlock();
            //textBlock.VerticalAlignment = VerticalAlignment.Center;
            //stack.Children.Add(textBlock);
            icon = new Image();
            icon.VerticalAlignment = VerticalAlignment.Center;
            icon.Margin = new Thickness(0, 0, 4, 0);
            icon.Source = iconSource;
            stack.Children.Add(icon);
            //Add the HeaderText After Adding the icon
            textBlock = new TextBlock();
            textBlock.VerticalAlignment = VerticalAlignment.Center;
            stack.Children.Add(textBlock);
    
        }
    
        #endregion Constructors and Destructors
    
        #region Properties
    
        /// <summary>
        /// Gets/Sets the Selected Image for a TreeViewNode
        /// </summary>
        public ImageSource Icon
        {
            set
            {
                iconSource = value;
                icon.Source = iconSource;
            }
    
            get
            {
                return iconSource;
            }
    
        }
    
        #endregion Properties
    
        #region Event Handlers
    
        /// <summary>
        /// Event Handler on UnSelected Event
        /// </summary>
        /// <param name="args">Eventargs</param>
        protected override void OnUnselected(RoutedEventArgs args)
        {
            base.OnUnselected(args);
            icon.Source = iconSource;
    
        }
        /// <summary>
        /// Event Handler on Selected Event 
        /// </summary>
        /// <param name="args">Eventargs</param>
        protected override void OnSelected(RoutedEventArgs args)
        {
            base.OnSelected(args);
            icon.Source = iconSource;
        }
    
        /// <summary>
        /// Gets/Sets the HeaderText of TreeViewWithIcons
        /// </summary>
        public string HeaderText
        {
            set
            {
                textBlock.Text = value;
            }
            get
            {
                return textBlock.Text;
            }
        }
    
    
        #endregion Event Handlers
    
    }
    
    
    SqlScript:
    
    USE [TreeView]
    GO
    /****** Object:  Table [dbo].[tblCountry]    Script Date: 05/27/2009 10:56:55 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[tblCountry](
    	[CountryId] [bigint] IDENTITY(100,1) NOT NULL,
    	[GameId] [bigint] NOT NULL,
    	[CountryName] [nvarchar](50) NOT NULL,
    	[Description] [nvarchar](100) NULL,
     CONSTRAINT [PK_tblCountry] PRIMARY KEY CLUSTERED 
    (
    	[CountryId] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    /****** Object:  Table [dbo].[tblPlayer]    Script Date: 05/27/2009 10:56:57 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[tblPlayer](
    	[PlayerId] [bigint] IDENTITY(500,1) NOT NULL,
    	[CountryId] [bigint] NOT NULL,
    	[PlayerName] [nvarchar](50) NOT NULL,
    	[Description] [nvarchar](100) NULL,
     CONSTRAINT [PK_tblPlayer] PRIMARY KEY CLUSTERED 
    (
    	[PlayerId] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    /****** Object:  Table [dbo].[tblGame]    Script Date: 05/27/2009 10:56:56 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[tblGame](
    	[GameId] [bigint] IDENTITY(1,1) NOT NULL,
    	[GameName] [nvarchar](50) NOT NULL,
    	[Description] [nvarchar](100) NULL,
     CONSTRAINT [PK_tblGame] PRIMARY KEY CLUSTERED 
    (
    	[GameId] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO
    /****** Object:  StoredProcedure [dbo].[sp_SelectTreeview]    Script Date: 05/27/2009 10:56:54 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author:		<Sarath Chandra>
    -- Create date: <Create Date,,>
    -- Description:	<Description,,>
    -- =============================================
    CREATE PROCEDURE [dbo].[sp_SelectTreeview] 
    AS
    BEGIN
    	Select GameId,GameName from TblGame 
        Select CountryId,GameId,CountryName from TblCountry
        Select * from TblPlayer
    END
    GO
    
    
    • Marked as answer by Vvg585 Wednesday, May 27, 2009 5:39 AM
    Wednesday, May 27, 2009 5:34 AM
  • Thanks Mr.Sarath Chandra It helps me a lot.
    Wednesday, May 27, 2009 7:04 AM
  • Hello , can somebody tell me how we can use this approach, so one checkbox at a time to can be checked? and how we can use the checked item to take the id of the node back?

     

     

    Thanks very much

    Saturday, August 28, 2010 3:53 PM
  • Hi Mr Sarath,

     

    for me "node.Icon = CreateImage(Path);" is not working it is not showing any image, instead when in debug is shows as "Metadata = {"BitmapMetadata is not available on BitmapImage."}"

     

    Please help.

    Thanks

    Madhoo

    Monday, April 11, 2011 11:28 AM
  • yes it is correct But i found some bug when i change the (My List) just like this

    Please give any soluation for this pl................

     

     myList.Add(new MyMenuItem(1, "Country", 0));

                myList.Add(new MyMenuItem(2, "U.S.A.", 1));

                myList.Add(new MyMenuItem(3, "India", 0));

                myList.Add(new MyMenuItem(10, "mj", 9));

                myList.Add(new MyMenuItem(4, "AP", 11));

                myList.Add(new MyMenuItem(5, "UP", 3));

                myList.Add(new MyMenuItem(6, "CA", 2));

                myList.Add(new MyMenuItem(7, "NY", 2));

                myList.Add(new MyMenuItem(8, "jj", 5));

                myList.Add(new MyMenuItem(9, "mj", 4));

                myList.Add(new MyMenuItem(11, "kk", 10));

                myList.Add(new MyMenuItem(12, "mj", 11));        

                 myList.Add(new MyMenuItem(13, "India", 0));

     

     

    Please give any soluation for this pl................


    joby James
    Friday, January 20, 2012 6:40 AM
  • Joby,

    I made some assumptions in my earlier post (The parent is listed before the child). so it makes

    myList.Add(new MyMenuItem(10, "mj", 9));

    out of order. It is referencing parentID of 9 which is not declared yet. So just after creating the List, just sort by ID:

    IEnumerable newList = myList.OrderBy( m => m.ID);

     

    This will Sort by ID and everything will work.


    noorbakhsh حميد نوربخش
    Friday, January 20, 2012 3:49 PM
  • I found your advice really helpful but I am having an order issue with my list.

    myList.Add(new MyMenuItem(1,Runcorn1,34)
    myList.Add(new MyMenuItem(3,Runcorn 2,34)
    myList.Add(new MyMenuItem(11,Runcorn 3,34)
    myList.Add(new MyMenuItem(16,test1,27)
    myList.Add(new MyMenuItem(17,test2,27)
    myList.Add(new MyMenuItem(18,Test3,17)
    myList.Add(new MyMenuItem(20,TOC,11)
    myList.Add(new MyMenuItem(27,Deleted Folders,0)
    myList.Add(new MyMenuItem(34,ICI,0)

    It should come out like this:-

    Deleted Folder
        Test1
        Test3
             Test3
    ICI
        Runcorn1
        Runcorn2
        Runcorn3
              TOC

    But in WPF it is like this:-

    Runcorn1
    Runcorn2
    Runcorn3
         TOC
    test1
    test2
         Test3
    Deleted Folders
    ICI

    Can you help me please?

    Wednesday, September 20, 2017 7:38 AM
  • Phil,

    You have to add them per level, so have to add the Deleted Folders and ICI first so their children can be added to them correctly. The parents have to either have IDs smaller than children and you can sort by ID to order them, or you have to add them in order. See my last reply.

    Hope this helps


    noorbakhsh حميد نوربخش


    • Edited by noorbakhsh Tuesday, September 26, 2017 5:16 PM
    Tuesday, September 26, 2017 4:58 PM
  • I'll have to reorganise in my table before hand somehow then.

    Trouble is I want the users to be able to move the folders around with drag and drop then update the parent value in sql table on drop.

    Thank you very much for your advice.

    Phil 

    Wednesday, September 27, 2017 12:28 PM
  • I used this code in Windows Forms but wondering if you can do similar in WPF?

        Private Sub PopulateRootLevel()

            Dim objConn As New SqlConnection(taggerDBserver)

            Dim objCommand As New SqlCommand("select FolderID,Folder_Name,locked,(select count(*) FROM Folder_Structure WHERE parentid=sc.FolderID) childnodecount FROM Folder_Structure sc where companyID = " & companyID & " And deleted = 'False'  And (parentid Is NULL) Order By FolderID", objConn)

            Dim da As New SqlDataAdapter(objCommand)

            Dim dt As New DataTable()

            TreeView1.Nodes.Clear()

            da.Fill(dt)

            PopulateNodes(dt, TreeView1.Nodes)

        End Sub

        Private Sub PopulateNodes(ByVal dt As DataTable, ByVal nodes As TreeNodeCollection)

            For Each dr As DataRow In dt.Rows

                Dim tn As New TreeNode()

                tn.Text = dr("Folder_Name").ToString()

                tn.Tag = dr("FolderID")

                Dim stringTag As String

                stringTag = tn.Tag.ToString

                PopulateSubLevel(stringTag, tn)

                nodes.Add(tn)

            Next

        End Sub

        Function populateTree()

            Dim sqlString As String

            sqlString = "SELECT * from Folder_Structure where companyID = " & companyID & " And deleted = 'False' order by dbo.GetLocationlevel(FolderID)"

            Dim DsSites1 As New DataSet

            Dim MyTestConnection1 As SqlConnection = New SqlConnection(taggerDBserver)

            Dim MyTestCommand1 As SqlDataAdapter = New SqlDataAdapter(sqlString, MyTestConnection1)

            MyTestConnection1.Open()

            MyTestCommand1.Fill(DsSites1, "sites")

            MyTestConnection1.Close()

            TreeView1.Nodes.Clear()

            Dim parentrow As DataRow

            Dim ParentTable As DataTable

            ParentTable = DsSites1.Tables("sites")

            For Each parentrow In ParentTable.Rows

                Dim parentnode As TreeNode

                parentnode = New TreeNode(parentrow.Item(2).ToString)

                parentnode.Text = parentrow.Item(2).ToString

                parentnode.Tag = parentrow.Item(0).ToString

                TreeView1.Nodes.Add(parentnode)

            Next parentrow

        End Function

        Private Sub PopulateSubLevel(ByVal parentid As String, ByVal parentNode As TreeNode)

            Dim objConn As New SqlConnection(taggerDBserver)

            Dim objCommand As New SqlCommand("select FolderID,Folder_Name,locked,(select count(*) FROM Folder_Structure WHERE parentid=sc.FolderID) childnodecount FROM Folder_Structure sc where companyID = " & companyID & " And parentID=@parentID And deleted = 'False'", objConn)

            objCommand.Parameters.Add("@parentID", SqlDbType.Char, 36).Value = parentid

            Dim da As New SqlDataAdapter(objCommand)

            Dim dt As New DataTable()

            da.Fill(dt)

            PopulateNodes(dt, parentNode.Nodes)

        End Sub

    Wednesday, September 27, 2017 12:53 PM