none
Loading images into a picturebox on treeview node click using c# .net????

    Question

  • Hi all,

    I m trying to develop an application. for ex Consider that i have a folder in C: dive named Pictures, which contains many images(jpeg,gif,bmp). i have a windows form. in that i have menustip. on click of the menu item build treeview,the tree structure of that Pictures folder sud be created in the tree view control displaying the names of the images. in the same form there will be a picture box. when the user double clicks on any of the image name in the treeview or when the user drags and drops that image name on to the picture box control, the selected image sud be displayed in the picture box. other thing that sud be included is, once the image is displayed, on mouse scroll, the image sud be zoomed in and out. the scrollbox sud be added automatically when the image is zoomed.

    the tree structure looks lik:

    -Pictures

         image1.jpg

         image2.jpg

         image3.gif

    can anyone please help me out to do this. i m in need of help.. pls help me at the earliest..

    Thanks a lot in advance

    Monday, February 28, 2011 3:07 PM

Answers

  • Hi,

    +-120 for the delta: Windows system defines the Mouse Wheel scroll one unit is 40 * 3 lines (we can change the 3 lines in control panel > Mouse setting). So the delta value is +-120 when we scroll one unit.

    -->  how to set the minimum and maximum size for zoom in and zoom out??

        private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
          int scale = 3;
          pictureBox.Dock = DockStyle.None;
          pictureBox.Width -= (e.Delta / 120 * scale);
          pictureBox.Height -= (e.Delta / 120 * scale);
          if (pictureBox.Width < 10)
            pictureBox.Width = 10;
          if (pictureBox.Width > 1000)
            pictureBox.Width = 1000;
          if (pictureBox.Height < 10)
            pictureBox.Height = 10;
          if (pictureBox.Height > 1000)
            pictureBox.Height = 1000;
        }
    
    Sincerely,
    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by abjohn Saturday, March 05, 2011 3:29 PM
    Thursday, March 03, 2011 10:02 AM

All replies

  • Hi,

    -Get a DirectoryInfo for the Folder that contains the images.

    -Set that path as Text of the root-node of the treeview.

    -Parse the FileInfos you get by calling GetFiles() for your DirectoryInfo and setup a node for each image with its name as text.

    -Handle the AfterSelect-Event for that Treeview and build the path to the images on disc by getting the Property FullPath for the Selected Treenode.

    -Display that image in the PictureBox by setting the Image-Property to it.

    -Implement a Handler for the MouseWheel-event and calculate the zoom by that.

    -Create a zoomed copy of the picture and redisplay the zoomed Image in the pictureBox.

    [you could also use a own Control derived from TreeView].

    Regards,

      Thorsten

    Monday, February 28, 2011 6:44 PM
  • Hi abjohn,

     This is a project but a question.

     

     Maybe I only give some snippet to help you finish the “question”.

    Base on your description

     

    First, you can load the folder which contains many images and display structured in your treeview.

     

    Please refer to the code:

    C# code

    DirectoryInfo dir=new DirectoryInfo(GetPathFromNode(node));

                    DirectoryInfo[] e=dir.GetDirectories();

                    FileInfo[] f=dir.GetFiles();

                    string name;

                    for(int i=0;i<e.Length;i++)

                    {

                        name=e[i].Name;

                        if(!name.Equals(".")&&!name.Equals(".."))

                        {

                            node.Nodes.Add(new DirNode(name));

                        }

                    }

                    for(int i=0;i<f.Length;i++)

                    {

                        name=f[i].Name;

                        node.Nodes.Add(new DirNode(name));

                    }

     

    Second, I think it is easy to implement double click to display the images into the picturebox.

    Third, handle the event so that you can make your image zoomed in and out.

    private void pictureBox1_MouseEnter(object sender, EventArgs e) {

            pictureBox1.Focus();

    }

     

    private void pictureBox1_MouseEnter(object sender, EventArgs e){

        pictureBox1.MouseWheel += new MouseEventHandler(pictureBox1_MouseWheel);

    }

     

    private void pictureBox1_MouseWheel(object sender, MouseEventArgs e){

      double scale = 1;

      if (pictureBox1.Height > 0) {

      scale = (double)pictureBox1.Width / (double)pictureBox1.Height;}

      pictureBox1.Width += (int)(e.Delta * scale);

      pictureBox1.Height += e.Delta;}

     

    }

    I hope it will help to you.

    And there is a relevance project which is alike with you want.

    http://cid-b3f8a9c14a55b00f.office.live.com/self.aspx/Work/TreeViewandpicturebox.zip

     Thanks for the blog:

    http://blog.stnn.cc/vcstudy/Efp_Bl_1001162031.aspx

    If you have any concerns, please free feel to follow up.

    Daniel Wan

    Tuesday, March 01, 2011 3:46 AM
  •  

    Error    1    The name 'GetPathFromNode' does not exist in the current context    C:\Documents and Settings\chr6kor\My Documents\Visual Studio 2008\Projects\tree3\tree3\Form1.cs    31    51    tree3
    Error    2    The name 'node' does not exist in the current context    C:\Documents and Settings\chr6kor\My Documents\Visual Studio 2008\Projects\tree3\tree3\Form1.cs    31    67    tree3
    Error    3    The name 'node' does not exist in the current context    C:\Documents and Settings\chr6kor\My Documents\Visual Studio 2008\Projects\tree3\tree3\Form1.cs    47    21    tree3
    Error    4    The type or namespace name 'DirNode' could not be found (are you missing a using directive or an assembly reference?)    C:\Documents and Settings\chr6kor\My Documents\Visual Studio 2008\Projects\tree3\tree3\Form1.cs    47    40    tree3
    Error    5    The name 'node' does not exist in the current context    C:\Documents and Settings\chr6kor\My Documents\Visual Studio 2008\Projects\tree3\tree3\Form1.cs    58    17    tree3
    Error    6    The type or namespace name 'DirNode' could not be found (are you missing a using directive or an assembly reference?)    C:\Documents and Settings\chr6kor\My Documents\Visual Studio 2008\Projects\tree3\tree3\Form1.cs    58    36    tree3

    i m getting these errors... :( can u pls help me wan

    Tuesday, March 01, 2011 6:55 AM
  • using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Diagnostics;
    using System.Reflection;

    namespace tree
    {
        public partial class Form1 : Form
        {
           
            public Form1()
            {
                InitializeComponent();
                PopulateTreeView();

            }

            private void Form1_Load(object sender, EventArgs e)
            {
               

            }
            private void PopulateTreeView()
            {
                TreeNode rootNode;
                string userpath;
                userpath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                userpath += "\\images";
                DirectoryInfo info = new DirectoryInfo(userpath);
                System.IO.FileInfo[] files = info.GetFiles("*.bmp");

                if (info.Exists)
                {
                    rootNode = new TreeNode(info.Name);
                    rootNode.Tag = info;
                    GetDirectories(info.GetDirectories(), rootNode);
                    treeView1.Nodes.Add(rootNode);
                }
            }


            private void GetDirectories(DirectoryInfo[] subDirs,
                TreeNode nodeToAddTo)
            {
                TreeNode aNode;
                DirectoryInfo[] subSubDirs;
                string userpath;
                userpath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                userpath += "\\images";
                DirectoryInfo info = new DirectoryInfo(userpath);
                System.IO.FileInfo[] files = info.GetFiles("*.bmp");
                foreach (DirectoryInfo subDir in subDirs)
                {
                    aNode = new TreeNode(subDir.Name, 0, 0);
                    aNode.Tag = subDir;
                    aNode.ImageKey = "folder";
                    subSubDirs = subDir.GetDirectories();
                    if (subSubDirs.Length != 0)
                    {
                        GetDirectories(subSubDirs, aNode);
                    }
                    nodeToAddTo.Nodes.Add(aNode);
                    

                }
            }

    }}

    i tired doing lik this.. i m getting only the folder name. i m not getting the list of images in that in the treeview. whats the mistake in this??

    Tuesday, March 01, 2011 8:26 AM
  • You'll have to add the files somehow:

      private void PopulateTreeView()
      {
       TreeNode rootNode;
       string userpath;
       userpath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
       userpath += "\\images";
       DirectoryInfo info = new DirectoryInfo(userpath);
       System.IO.FileInfo[] files = info.GetFiles("*.png");
    
       if (info.Exists)
       {
        rootNode = new TreeNode(info.Name);
        rootNode.Tag = info;
        treeView1.Nodes.Add(rootNode);
    
        foreach(DirectoryInfo subDir in info.GetDirectories())
         GetDirectories(subDir, rootNode);
    
        GetFiles(info.GetFiles("*.png"), rootNode); 
       }
      }
    
      private void GetDirectories(DirectoryInfo dir, TreeNode nodeToAddTo)
      {
       TreeNode aNode;
       aNode = new TreeNode(dir.Name, 0, 0);
       aNode.Tag = dir.FullName;
       aNode.ImageKey = "folder";   
       nodeToAddTo.Nodes.Add(aNode);
    
       foreach (DirectoryInfo subDir in dir.GetDirectories())
       {
        GetDirectories(subDir, aNode);
       }
    
       GetFiles(dir.GetFiles("*.png"), aNode); 
      }
    
      private void GetFiles(FileInfo[] files,TreeNode nodeToAddTo)
      {
       TreeNode aNode;
       foreach (FileInfo fi in files)
       {
        aNode = new TreeNode(fi.Name, 0, 0);
        aNode.Tag = fi.FullName;
        aNode.ImageKey = "file";
        nodeToAddTo.Nodes.Add(aNode);
       }
      }
    

    *But*: This way has a great disadvantage: the performance (if the directorytree is a larger one). It is better to fill-up the directories and files for only 2 steps down. You can do this by handling the OnBeforeExpand and Collapse (or the AfterExpand and Collapse) events. Some years ago there was a very good microsoft example out doing this, I *think* the name was something like "How to create an ExplorerStyleViewer" (has been in a 101-samples pack). If I find a link I'll post it here.

    Regards,

      Thorsten

    Tuesday, March 01, 2011 8:18 PM
  • This could be it: (VB though)

    Update: Yes, it is it :-)

    http://www.microsoft.com/downloads/en/details.aspx?FamilyID=b81b034a-881b-4206-aa0b-c2e09dcd1d2f&displaylang=en

    Regards,

      Thorsten

    Tuesday, March 01, 2011 8:22 PM
  • Hi everybody,

    I have a change for the program.

    Take a look at the link:

    http://cid-b3f8a9c14a55b00f.office.live.com/self.aspx/Work/TreeView%5EMpictureBox.zip

    Regards

    Daniel Wan

    Wednesday, March 02, 2011 3:38 AM
  • i tried doing like this... is this ok????

     

    private void PopulateTreeView()
            {
                string userpath;
                userpath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                userpath += "\\Maps";

                DirectoryInfo startFolder = new DirectoryInfo(userpath);
                TreeNode rootNode = m_otreeViewMaps.Nodes.Add(startFolder.Name);

                CreateFileSystemNodes(rootNode, startFolder);
            }

            private void CreateFileSystemNodes(TreeNode currentNode, DirectoryInfo currentFolder)
            {
                // add all sub-folders within the current folder
                foreach (DirectoryInfo subfolder in currentFolder.GetDirectories())
                {
                    TreeNode subFolderNode = currentNode.Nodes.Add(subfolder.Name);
                    CreateFileSystemNodes(subFolderNode, subfolder);
                }

                // add the files within the folder
                foreach (FileInfo file in currentFolder.GetFiles())
                {
                    currentNode.Nodes.Add(file.Name);
                }
            }  

     

    pls let me if the logic is ok...... on click of the image in treeview the image sud be displayed in the picturebox.. how to handle that???? pls can anyone tell me how to do this?????

    pls.. thanks a lot for the help.

     

    Regards,

    John

    Wednesday, March 02, 2011 5:25 AM
  • Hi John,

    Yes, from the code you post above, it seems can populate all file nodes into one TreeView. So next, we just need to implement an event handler on the TreeViewNode, such as AfterSelect event of the TreeView. And then we could get the file path, to load the file as image and show it in the PictureBox. Like the code in Daniel's sample, treeViewDir_AfterSelect event handler could be fired when user select one node of the TreeView. His method GetPathFromNode can return the file path of the selected node, we could create a bitmap instance of the selected file by code:

    Bitmap bitmap=new Bitmap(fileName);
    pictureBox.Image=bitmap;
    
    Sincerely,
    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, March 02, 2011 8:57 AM
  • Hello Bob,

    how to check if the selected node in the treeview is a folder or a file.??? if it is a file, say an image, then only it sud be loaded into the picture box...

     

    pls help me to solve this....

     

    Regards,

    John

     

    Wednesday, March 02, 2011 12:16 PM
  •  

    Hi,

    I tried doing lik Daniel.. the image is getting loaded properly and the zoom property is also working fine. but if i try to move the mouse wheel more i.e if i try to move the mouse wheel backward more, then i m getting this exception. if i try to move the mouse wheel forward more then the image is getting disappeared. how to set the minimum and maximum size for zoom in and zoom out?? because even if i try to zoom out the image, after it has reached minimum size it sud not become still small. the exception which i am getting is attached below:

    InvalidOperationException was unhandled.

    BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress.

    i have set the scroll bars for the panel, so that can see the full image even if it is zoomed very much.

    one more doubt is how is that height and width calculated???? delta is -120.. how is it chosen???

    pls help me to solve the exception, image disappearing prob and help me to understand the calculation of mouse wheel movement.

    Thanks for the help.....

     

    Regards,

    John

    Wednesday, March 02, 2011 5:56 PM
  • Hi,

    +-120 for the delta: Windows system defines the Mouse Wheel scroll one unit is 40 * 3 lines (we can change the 3 lines in control panel > Mouse setting). So the delta value is +-120 when we scroll one unit.

    -->  how to set the minimum and maximum size for zoom in and zoom out??

        private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
          int scale = 3;
          pictureBox.Dock = DockStyle.None;
          pictureBox.Width -= (e.Delta / 120 * scale);
          pictureBox.Height -= (e.Delta / 120 * scale);
          if (pictureBox.Width < 10)
            pictureBox.Width = 10;
          if (pictureBox.Width > 1000)
            pictureBox.Width = 1000;
          if (pictureBox.Height < 10)
            pictureBox.Height = 10;
          if (pictureBox.Height > 1000)
            pictureBox.Height = 1000;
        }
    
    Sincerely,
    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by abjohn Saturday, March 05, 2011 3:29 PM
    Thursday, March 03, 2011 10:02 AM
  • Hey BOB,

    thanks for the solution.. the Mouse Wheel scroll one unit is 40 * 3 lines.  

    where is this 40 defined??? is it user defined???

    Regards,

    John

    Saturday, March 05, 2011 3:28 PM
  • It is defined by the Windows system. Not user defined.
    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Sunday, March 06, 2011 11:47 PM