CSharp .Net Tutorial: Picture Box Load Icon

James Cloud
The Picture Box control that comes with Visual CSharp .Net does not allow the developer to easily load an icon file into the picture box's image. Picture Boxes can be a convenient way of display images anywhere on your form and changing or manipulating these images. However, if you wanted to load an Icon file into a your picture box you will find that you cannot do this by using the load picture file dialog box.

This tutorial will teach you how to make an easily reusable function that will load any icon file into a picture box controls in Visual CSharp .Net.

Loading Icons into Picture Box

To be able to create the icon loading void you will need to add two references before your namespace. These references are System Drawing and System IO. Add them like so:

using System.IO;
using System.Drawing;

Now, that you have the proper references, create a public void called LoadIcon with a PictureBox parameter called PicBox and a String parameter called IconPath. Use this source code to make the void:

public void LoadIcon(PictureBox PicBox, String IconPath)
{
//Initialize temporary images and icons
System.Drawing.Image icoIMG = null;
System.Drawing.Icon tmpICO = new System.Drawing.Icon(IconPath);

//Create an Imagelist to Hold the Icon
ImageList tmpImgLst = new ImageList();

tmpImgLst.Images.Add(tmpICO);
icoIMG = tmpImgLst.Images[0];

PicBox.Image = icoIMG;
}

The function that you created will load the specified icon file into an image list and then load the image from the image list into the picture box. Thus allowing you to easily load icon files into a Picture Box control.

Conclusion

With the proper function all you need to do is call the LoadIcon method and supply your desired picture box as the first parameter and the string path to your icon as the second parameter. Here is an example:

LoadIcon(picIcon, "C:\\My Images\\smiley.ico");

This will load the icon file, C:\My Images\smiley.ico, into the picture box, picIcon.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.