Creating Array of PictureBox controls in C#


Introduction

In VB6 we can create many Controls (Label, TextBox, Button, PictureBox, …etc.) as Array, but Visual Studio .NET not support this work. I try to create Array of PictureBox controls in this article, you can create array of Labels and Buttons as my example.

About my project 

My project has two Forms, name of one is (frmThumb) and name of other is (frmView).

With the first form you can load all images from any folder as Thumbnail by click the button (Load images). Then, when Click any image you can view this image with own size on the form (frmView).

The form (frmThumb) has: 

one Panel control (BackPanel) to hold images,

Progress control (MyProgress ) work while images are loading,

Two buttons: one (btnLoad) to load images, other (btnExit) to exit Application.

The form (frmView) has: 

One pictureBox control (imgDisplay) to view the image which you click, I let the property SizeMode = AutoSize,

label (lblImageName) to view the name and full path of the image,

button (btnClose) to close the form and return to the form (frmThumb).

How it works

// First, to create the array of Picture control
// Function to add PictureBox controls, You can determine number of controls
//
private void AddControls(int cNumber)
{
    // assign number of controls (cNumber):
    imgArray = new System.Windows.Forms.PictureBox[cNumber];
    for (int i = 0; i < cNumber; i++)
    {
        // Initialize one variable
        imgArray[i] = new System.Windows.Forms.PictureBox();
    }
}
//
// The Event of Click Button:
//
private void ClickImage(Object sender, System.EventArgs e)
{
    // On Click: load (ImageToShow) with (Tag) of the image, Tag of image // is its name and path
    ImageToShow = ((System.Windows.Forms.PictureBox)   sender).Tag.ToString;
    // then view this image on the form (frmView)
    Thumbnail.frmView f = new Thumbnail.frmView();
    f.ShowDialog();
}
//
// Event of the image click:
//
imgArray[i].Click += new System.EventHandler(ClickImage);
/* You can read about the Functions:
ImagesInFolder() to load images from any folder,
ShowFolderImages() to view images as Thumbnail and how write Tag of the image as following:*/
//
// You can set the Tag = name and full path of image,
// also you can set the Tag = number of the image in its array.
// Now we set the Tag = name and full path of the image
imgArray[i].Tag = imgName[i];
//
// add images to Panel:
//
this.BackPanel.Controls.Add(imgArray[i]);

Remarks

The file ImageArray.zip contains:

Source files of this article and the folder of some images in ..\ImageArray\bin\Debug\Images.

I hope this article helps you to create array of any control Label, TextBox or Button. If you have any idea let me know and if you find any problem you can tell me.

Thanks for c-sharpcorner team and for all.