CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 28

Thread: Treeview

  1. #1
    Join Date
    Apr 2004
    Posts
    265

    Treeview

    Hi,
    I would like to add a Treeview control in VB.NET 2005 and display a particular folder and all the folders under that folder in the treeview. How can I do that? Please help.

    Thanks

  2. #2
    Join Date
    Sep 2006
    Posts
    392

    Re: Treeview

    VS 2005

  3. #3
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Re: Treeview

    The following code VB 2005 segment will Create Nodes for each folder and then list all the files (within that folder) as childnodes. It should be what you need
    Code:
    Imports System.IO
    Public Class Form1
    
        Private Sub LoadTree()
            Dim FolderNode As TreeNode
            Dim FilePath As String
            Dim FolderPath As String
    
            Me.Cursor = Cursors.WaitCursor
    
            For Each FolderPath In Directory.GetDirectories("C:\Hannes", "*") 'specify your OWN path here
                FolderNode = TreeView1.Nodes.Add(Path.GetFileName(FolderPath))
    
                For Each FilePath In Directory.GetFiles(FolderPath)
    
                    FolderNode.Nodes.Add(Path.GetFileName(FilePath))
    
                Next
            Next
            Me.Cursor = Cursors.Arrow
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            LoadTree()
        End Sub
    End Class
    Last edited by HanneSThEGreaT; March 7th, 2007 at 10:13 AM.

  4. #4
    Join Date
    Apr 2004
    Posts
    265

    Re: Treeview

    Yes! This is what I wanted. But I don't see the sub folders inside the folders that are displayed. I can only see the files in the folders. Please help.

    Thanks

  5. #5
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Re: Treeview

    OK, this changes the ball game a bit. I apologise for not reading your first post correctly If I did, it would have been solved by now

    Anyways, have a look at the next code segment. It shows ALL the Folders AND subfolders within that folder - if the subfolder has more folder in it, it WILL show all the folders in it as well.
    Code:
    Imports System.IO
    Public Class Form1
    
        Private Sub AddAllFolders(ByVal node As TreeNode, ByVal path As String)
    
            Try
                For Each FolderNode As String In Directory.GetDirectories(path)
                    Dim SubFolderNode As TreeNode = node.Nodes.Add(FolderNode.Substring(FolderNode.LastIndexOf("\"c) + 1))
                    SubFolderNode.Tag = FolderNode
                    SubFolderNode.Nodes.Add("Loading...")
                Next
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
    
        End Sub
    
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim Tnode As TreeNode = TreeView1.Nodes.Add("(Drive C:)")
            AddAllFolders(Tnode, "C:\")
    
        End Sub
    
        Private Sub Treeview1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
            If Not TreeView1.SelectedNode Is Nothing Then
            Else
    
                If TreeView1.SelectedNode.Nodes.Count = 1 AndAlso TreeView1.SelectedNode.Nodes(0).Text = "Loading..." Then
    
                    TreeView1.SelectedNode.Nodes.Clear()
    
                    AddAllFolders(TreeView1.SelectedNode, CStr(TreeView1.SelectedNode.Tag))
                End If
    
                Dim folder As String = CStr(TreeView1.SelectedNode.Tag)
    
                If Not folder Is Nothing AndAlso IO.Directory.Exists(folder) Then
                    Try
                        For Each file As String In IO.Directory.GetFiles(folder)
    
                        Next
                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try
                End If
    
            End If
    
        End Sub
    
        Private Sub Treeview1_BeforeExpand(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
    
            If e.Node.Nodes.Count = 1 AndAlso e.Node.Nodes(0).Text = "Loading..." Then
    
                e.Node.Nodes.Clear()
                AddAllFolders(e.Node, CStr(e.Node.Tag))
            End If
        End Sub
    End Class
    Have fun!

  6. #6
    Join Date
    Apr 2004
    Posts
    265

    Re: Treeview

    It works fine. But I noticed that the sub folders are not in ascending order. Also, I would like to get the folder icons too along with the folder names.

    Thanks

  7. #7
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Re: Treeview

    To sort a Treeview, simply call the Treeview's Sort method

    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim Tnode As TreeNode = TreeView1.Nodes.Add("(Drive C:)")
            AddAllFolders(Tnode, "C:\")
            TreeView1.Sort()
        End Sub

  8. #8
    Join Date
    Mar 2004
    Posts
    223

    Re: Treeview

    Icon.ExtractAssociatedIcon() can be sued to retrieve file icons.
    Dir icons to be extracted by using Shell functions - SHGetFileInfo() would help.

    In C#, this is a beautiful link - it explains it all -clearly.

    basically, the class:

    Code Courtesy by : Eli Gazit

    Code:
    class IconExtractor
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct SHFILEINFO
            {
                public IntPtr hIcon;
                public IntPtr iIcon;
                public uint dwAttributes;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
                public string szDisplayName;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
                public string szTypeName;
            };
            
            class Win32
            {
                public const uint SHGFI_ICON = 0x100;
                public const uint SHGFI_LARGEICON = 0x0;    // 'Large icon
                public const uint SHGFI_SMALLICON = 0x1;    // 'Small icon
    
                [DllImport("shell32.dll")]
                public static extern IntPtr SHGetFileInfo(string pszPath,
                                            uint dwFileAttributes,
                                            ref SHFILEINFO psfi,
                                            uint cbSizeFileInfo,
                                            uint uFlags);
            }   
           
            /// <summary>
            /// Gets the icon asotiated with the filename.
            /// </summary>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static Icon GetFileIcon(string fileName, IconSize _iconSize)
            {
                System.Drawing.Icon myIcon = null;
                try
                {
                    IntPtr hImgSmall;    //the handle to the system image list
                    SHFILEINFO shinfo = new SHFILEINFO();
    
                    //Use this to get the small Icon
                    hImgSmall = Win32.SHGetFileInfo(fileName, 0, ref shinfo,
                                                    (uint)Marshal.SizeOf(shinfo),
                                                    Win32.SHGFI_ICON |
                                                   (_iconSize == IconSize.Small ? Win32.SHGFI_SMALLICON : Win32.SHGFI_LARGEICON) );
    
                    //The icon is returned in the hIcon member of the shinfo
                    //struct
                    myIcon =
                            System.Drawing.Icon.FromHandle(shinfo.hIcon);
                }
                catch
                {
                    return null;
                }
                return myIcon;
            }   
        }
    Explained here:

    http://www.codeproject.com/cs/miscctrl/FilesListBox.asp

    [If you find my answers useful, please leave your comments and rating for it.]
    Happy Coding!
    My Dev.: MS VS 2005 Version 8.0.50727.42 .NET 2.0.50727
    Mark your answers Tools>>RESOLVED once its answered.

  9. #9
    Join Date
    Apr 2004
    Posts
    265

    Re: Treeview

    The sort worked.

    Sorry, I'm not very familiar with C#. Could you please give me a VB.Net example?

    Thanks

  10. #10
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Smile Re: Treeview

    shers, This kept me busy for a while

    What I used here was :
    The SHFILEINFO structure
    The SHGetFileInfo API function

    And the following Constants:
    SHGFI_ICON
    SHGFI_SMALLICON

    I added an Imagelist to the Form, and set the Treeview's ImageList property to the name of my ImageList.

    I then created a sub to Add all the associated folder icons to the ImageList.
    Here is the new code (The old code is still in tact, I'm just demonstrating the new code) :
    I added this Import
    Code:
    Imports System.Runtime.InteropServices
    The Constants, API, and the new sub :
    Code:
        Private Structure SHFILEINFO
            Public hIcon As IntPtr            ' : icon
            Public iIcon As Integer           ' : icondex
            Public dwAttributes As Integer    ' : SFGAO_ flags
            <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
            Public szDisplayName As String
            <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
            Public szTypeName As String
        End Structure
    
        Private Declare Auto Function SHGetFileInfo Lib "shell32.dll" _
                (ByVal pszPath As String, _
                 ByVal dwFileAttributes As Integer, _
                 ByRef psfi As SHFILEINFO, _
                 ByVal cbFileInfo As Integer, _
                 ByVal uFlags As Integer) As IntPtr
    
        Private Const SHGFI_ICON = &H100
        Private Const SHGFI_SMALLICON = &H1
        Private Const SHGFI_LARGEICON = &H0    ' Large icon
        Private Const MAX_PATH = 260
        Private nIndex = 0
    
        Private Sub AddImages(ByVal strFileName As String)
    
            Dim shInfo As SHFILEINFO
            shInfo = New SHFILEINFO()
            shInfo.szDisplayName = New String(vbNullChar, MAX_PATH)
            shInfo.szTypeName = New String(vbNullChar, 80)
            Dim hIcon As IntPtr
            hIcon = SHGetFileInfo(strFileName, 0, shInfo, Marshal.SizeOf(shInfo), SHGFI_ICON Or SHGFI_SMALLICON)
            Dim MyIcon As Drawing.Bitmap
            MyIcon = Drawing.Icon.FromHandle(shInfo.hIcon).ToBitmap
            ImageList1.Images.Add(MyIcon)
    
            nIndex = nIndex + 1
    
        End Sub
    OK, yes, I know I didn't declare the SHGetFileInfo API the proper .NET way, but I think you can forgive me

    Then, the call to the AddImages sub is done in the "old" AddAllFolders sub. Here's what the AddAllFolders sub looks like now :
    Code:
        Private Sub AddAllFolders(ByVal node As TreeNode, ByVal path As String)
            Dim iIndex As Integer
            Try
                For Each FolderNode As String In Directory.GetDirectories(path)
    
                    Dim SubFolderNode As TreeNode = node.Nodes.Add(FolderNode.Substring(FolderNode.LastIndexOf("\"c) + 1))
    
                    SubFolderNode.Tag = FolderNode
    
                    SubFolderNode.Nodes.Add("Loading...")
    
                    AddImages(SubFolderNode.Tag)
                    SubFolderNode.ImageIndex = iIndex
                    SubFolderNode.SelectedImageIndex = iIndex
                    iIndex = iIndex + 1
                Next
    
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
    
        End Sub
    The rest is still the same as in my previous posts..

    I'm attaching the Project with, and I surely hope that it helps you
    Last edited by HanneSThEGreaT; March 14th, 2007 at 07:37 AM. Reason: Removed Attachment

  11. #11
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Re: Treeview

    shers, It seems like there's a slight problem with the above, the folder icons are sometimes at the wrong place.
    Give me a few minutes (hopefully not hours) and it should be sorted out....

  12. #12
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Re: Treeview

    Why struggle when Microsoft already made a sample about this

    Here you can find the .NET Fraemwork 1.1 version.

    You can do exactly the same in VB 2005
    If you do not have VB 2003, then simply open this project with VB.NET 2005, and it will upgrade it for you .
    Last edited by HanneSThEGreaT; March 14th, 2007 at 07:40 AM. Reason: removed Attachment

  13. #13
    Join Date
    Apr 2004
    Posts
    265

    Re: Treeview

    Hannes,
    Thanks so much for the time you spent on finding out a solution. I will be more clear on what I am intending to do, so that I will not waste your precious time. So far everything is ok till the code just above the last post. But in the last post, the code is to extract all icons, which I don't think I will need. My intention is to display all the folders in a particular folder on the left panel, that is, the Treeview and if any of the folders have AutoCAD drawings, to display only AutoCAD drawing files on the right panel, that is, the ListView.

    Thanks

  14. #14
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Re: Treeview

    Hi shers!
    It's only a pleasure

    OK, now I see what you want to do. I was a bit uncertain if you wanted all the icons, or not

    What I'll do, is to expand on my code in post #10, and see if I can include that. It's actually not too difficult All we will need to determine is the Autocad files.
    In order to that, I will need to know the file extension of an AutoCAD file; as I'm not too familiar with it.
    In SA, that package costs over R 30 000

  15. #15
    Join Date
    Apr 2004
    Posts
    265

    Re: Treeview

    Oops! 30000? Anyways, the file extension for AutoCAD is .dwg.

    Thanks

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured