Previous Tip  |  Next Tip  |  Design Tips   | [Bill's Home]

207. Adding interest to TreeViews

A previous design tip outlined how a tree view enhanced the presentation of menu items, such as:

An excellent enhancement is to add graphics to the tree view elements, so that they change for the different levels, or whether they are selected, or not, such as:

Notice that the selected item can use a different graphic. If you look closely the default treeView gives:

but with a small addition of coding it changes to:

The code to achieve this is fairly simple, such as:

ImageList myImageList = new ImageList();

myImageList.Images.Add(Image.FromFile("smallr.gif"));
myImageList.Images.Add(Image.FromFile("smallr2.gif"));
myImageList.Images.Add(Image.FromFile("smallr3.gif"));
myImageList.Images.Add(Image.FromFile("smallr4.gif"));

treeView1.ImageList = myImageList;

treeView1.ImageIndex = 0;
treeView1.SelectedImageIndex = 1;

where the ImageIndex property is the image to be displayed (0 selects smallr.gif), and the SelectedImageIndex defines the image to be displayed once it is selected (1 selects smallr2.gif).