Expanding TreeView Nodes

Posted on 2005-04-13
Last Modified: 2008-06-03
I am currently writing a custom control for a project that emulates windows explorer. This control has a TreeView which contains the folder structure of the system. Instead of loading each and every one of the file systems folders into this TreeView at startup, I have it so that when a node is clicked, it automatically creates child nodes from that nodes path (the path being contained in the nodes tag). I am using the AfterSelect event of the tree view to handle this operation.

The problem I am having is when I click on the Plus sign next to a node and expand it, my method for adding sub directories to that node does not fire off. If I actually select the node's icon (or text), it works just fine. I have tried using the AfterExpand event in addition to AfterSelect, but no dice. I even tried using BeforeSelect and BeforeExpand, but no dice there either.

Does anyone have any suggestions on how I can get the TreeView to respond when I expand a node? I'm sure it's easy, but I'm at a loss here. I hope this makes sense.
Question by:Thora_Fan
    LVL 6

    Accepted Solution

    I have tried event BeforeExpand and it work well.
    Here is example code

    using System.IO;
    using System.Windows.Forms;
    using System.Drawing;

    class DirectoryTreeView: TreeView

        // This is the class constructor.

        public DirectoryTreeView () {

            // Make a little more room for long directory names.

            this.Width *= 2;

            // Get images for tree.

            this.ImageList = new ImageList();

                this.ImageList.Images.Add(new Bitmap(@"..\..\ExplorerStyleViewer\35FLOPPY.BMP"));
                this.ImageList.Images.Add(new Bitmap(@"..\..\ExplorerStyleViewer\CLSDFOLD.BMP"));
                this.ImageList.Images.Add(new Bitmap(@"..\..\ExplorerStyleViewer\OPENFOLD.BMP"));
                // Construct tree.

        // the BeforeExpand event for the subclassed TreeView. See further
        // comments about the Before_____ and After_______ TreeView event pairs in
        // /DirectoryScanner/DirectoryScanner.cs.

        protected override void OnBeforeExpand(TreeViewCancelEventArgs tvcea)


            // For performance reasons and to avoid TreeView "flickering" during an
            // large node update, it is best to wrap the update code in BeginUpdate...
            // EndUpdate statements.


            // Add child nodes for each child node in the node clicked by the user.
            // For performance reasons each node in the DirectoryTreeView
            // contains only the next level of child nodes in order to display the + sign
            // to indicate whether the user can expand the node. So when the user expands
            // a node, in order for the + sign to be appropriately displayed for the next
            // level of child nodes, *their* child nodes have to be added.

                foreach(TreeNode tn in tvcea.Node.Nodes)


        // This subroutine is used to add a child node for every directory under its
        // parent node, which is passed an argument. See further comments in the
        // OnBeforeExpand event handler.

        void AddDirectories(TreeNode tn)


            string strPath = tn.FullPath;

            DirectoryInfo diDirectory = new DirectoryInfo(strPath);
                DirectoryInfo[] adiDirectories;

            try {

                // Get an array of all sub-directories DirectoryInfo objects.

                adiDirectories = diDirectory.GetDirectories();

           } catch

            foreach(DirectoryInfo di in adiDirectories)

                // Create a child node for every sub-directory, passing in the directory
                // name and the images its node will use.

                TreeNode tnDir = new TreeNode(di.Name, 1, 2);

                // Add the new child node to the parent node.


                // We could now fill up the whole tree by recursively calling
                // AddDirectories():
                //   AddDirectories(tnDir)
                // This is way too slow, however. Give it a try!


        // This subroutine clears out the existing TreeNode objects and rebuilds the
        // DirectoryTreeView, showing the logical drives.

        public void RefreshTree()

            // For performance reasons and to avoid TreeView "flickering" during an
            // large node update, it is best to wrap the update code in BeginUpdate...
            // EndUpdate statements.


            // Make disk drives the root nodes.

            string[] astrDrives = Directory.GetLogicalDrives();

            foreach(string strDrive in astrDrives)
                      TreeNode tnDrive = new TreeNode(strDrive, 0, 0);

                // Set the C drive the default selection.
                if (strDrive == @"C:\")
                    this.SelectedNode = tnDrive;

    Author Comment

    Thanks. The problem I was having was that I WASN'T adding sub nodes right away. Did that and it fixed the problem.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
    Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now