Thursday, April 22, 2010

Code4Food #4: How to change WinForms Treeview control image size?

Hi,

Today I visited Bytes.com and saw a question about Treeview.

Indeed how would one change ImageSize of a node ? So I had 15 free minutes and this is what I found.

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;

namespace TreeView.ImageSize
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            FillTreeView();
        }

        private void FillTreeView()
        {
            // Load the images in an ImageList.
            ImageList myImageList = new ImageList();
            myImageList.Images.Add(Image.FromFile("63vts4.jpg"));
            myImageList.Images.Add(Image.FromFile("ToDeleteIfNotSold.png"));
            
            // Change the size of the images.
            myImageList.ImageSize = new Size(50, 50);

            // Assign the ImageList to the TreeView.
            trvImages.ImageList = myImageList;
            trvImages.ItemHeight = 50;

            // Set the TreeView control's default image and selected image indexes.
            trvImages.ImageIndex = 0;
            trvImages.SelectedImageIndex = 1;

            // Create the root tree node.
            TreeNode rootNode = new TreeNode("CustomerList");

            TreeNode childNode1 = new TreeNode("Customer1");
            TreeNode childNode2 = new TreeNode("Customer2");

            // Add a main root tree node.
            trvImages.Nodes.Add(rootNode);
            trvImages.Nodes[0].Nodes.Add(childNode1);
            trvImages.Nodes[0].Nodes.Add(childNode2);
        }
    }
}

So the magic line was myImageList.ImageSize = new Size(50, 50); Here is the output and the code to download.

Download source code link

3 comments:

  1. Thx a lot. Since ImageList & TreeView are separate, runtime code for some properties do not auto-update.

    These 3 properties are quite important (I added some extra info too) :

    ImageList.ImageSize = new Size(x,x)
    TreeView.ItemHeight = x
    TreeView.Indent = (x + 3)

    ----
    Focuscar

    ReplyDelete