Click here to Skip to main content
15,878,430 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

1)
I develop a c# user control.
In that control, I have a button. When the user clicks the button at runtime, a new control (for example, pictureBox) is created ,next to the previous pictureBox.

I did it that way:

C#
PictureBox pb = new PictureBox();
pb.Location = new Point(oldPb.X, oldPb.Y + 100);
pb.Size = oldPb.Size;
Controls.Add(pb);


The problem is, that I want to be able to manage all of the created items.
I want, for example, to index the pictureBoxes, then get a number from the user and change the photo of the wanted photoBox.
for example:

C#
photoBox3.Image = .......


How can I do it?

2)
I want to be able to recognize when the user clicks on one of those photoBoxes and do an action on the chosen photoBox.
How can I do that?

Thanks
Posted
Updated 14-Oct-12 1:46am
v2

1 solution

Add a List to you UserControl:
C#
private List<PictureBox> Pictures = new List<PictureBox>();


Then when you add it to the controls list, you also add it to the Pictures:
C#
PictureBox pb = new PictureBox();
pb.Location = new Point(oldPb.X, oldPb.Y + 100);
pb.Size = oldPb.Size;
Controls.Add(pb);
Pictures.Add(pb);
When you want to access it, you can do it by index, in the order you added them:
C#
PictureBox toChange = Pictures[3];
(Obviously, you will want to make sure there are enough PictureBoxes in the list with the Count property before you try to get it!)
 
Share this answer
 
Comments
[no name] 14-Oct-12 9:11am    
I think List of Control will be more efficient, isn't it?
My 4!
OriginalGriff 14-Oct-12 9:32am    
You already have a List of Control objects - the Control.Controls list. However, this contains all controls, not just the PictureBoxes the OP is talking about. Which means that you have to look through the list checking if each Control is a PictureBox when you what to access them.

Using a Generic List as a second list of Control types instead of making is a strongly typed list of PictureBoxes is not more efficient - in fact it requires extra work to convert it's content back to a PictureBox when you actually want to use them.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900