[RESOLVED] accessing controls in a loop
Hi,
I have 6 pictureboxes on my form to display random pictures in.
I use several functions to load pictures, clear pictures etc. All of these functions have all 6 pictureboxes hardcoded.
For example:
Code:
private void ShowPics()
{
this.pictureBox1.Image = this.pictures[this.rnd.Next(0, this.pictures.Length)];
this.pictureBox2.Image = this.pictures[this.rnd.Next(0, this.pictures.Length)];
this.pictureBox3.Image = this.pictures[this.rnd.Next(0, this.pictures.Length)];
this.pictureBox4.Image = this.pictures[this.rnd.Next(0, this.pictures.Length)];
this.pictureBox5.Image = this.pictures[this.rnd.Next(0, this.pictures.Length)];
this.pictureBox6.Image = this.pictures[this.rnd.Next(0, this.pictures.Length)];
}
So if I wanted to add more pictureboxes I'd have to add lines to all those functions (for pictureBox6, 7, ...). Is there a more dynamic way to access each picturebox in a loop or arrayList or something?
Re: accessing controls in a loop
How about an For i = 0 To 5 loop?
Re: accessing controls in a loop
hi look at this example:
Code:
foreach (Control ctrl in this.Controls)
{
if (ctrl is PictureBox)
{
MessageBox.Show(ctrl.Name);
}
}
this will display al the picturebox names in your form.so like this u can loop through your contols in your page
Re: accessing controls in a loop
Hack,
How would you use the for loop with separate controls?
karthikeyan,
This works for .Name but not for .Image of the picturebox
Re: accessing controls in a loop
That's because it's still being seen as an object. Try something more like this:
csharp Code:
foreach (Control ctrl in this.Controls)
{
if (ctrl is PictureBox)
{
PictureBox pb = (PictureBox)ctrl; //cast it as a PictureBox to expose the right properties
MessageBox.Show(pb.Image);
}
}
Re: accessing controls in a loop
Casting worked. Thanks.
I was hoping that I wouldn't have to go through all controls to find the boxes. I wonder how efficient would it be with lots of controls on the form.
Re: [RESOLVED] accessing controls in a loop
No problem. Casting is an essential in C#. Probably the majority of type operations will involve some form of cast, otherwise C# won't know what type of object it's dealing with. Rather, it'll be dealing with the object type itself, and not the type you want it to.
Re: [RESOLVED] accessing controls in a loop
If you want to loop through a number of controls then create an array of controls in code:
Code:
private PictureBox[] pictureBoxes;
public Form1()
{
InitializeComponent();
this.pictureBoxes = new PictureBox[] { this.pictureBox1,
this.pictureBox2,
this.pictureBox3 };
}