Reputation: 391
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:
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:
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
Upvotes: 0
Views: 208
Reputation: 116138
List<PictureBox> pictureBoxes = new List<PictureBox>();
for (int i = 0; i < 10; i++)
{
PictureBox pb = new PictureBox();
pb.Location = new Point(.....);
pb.Size = ......;
pb.Click += pb_Click;
Controls.Add(pb);
pictureBoxes.Add(pb);
}
pictureBoxes[3].Image=..... //Use like this
void pb_Click(object sender, EventArgs e)
{
PictureBox pb = sender as PictureBox;
//Do work
}
Upvotes: 1
Reputation: 17395
You can use the Tag
Property of the PictureBox to store some kind of index.
You can then have all your PictureBoxes respond to a click event:
pb.Click += new EventHandler(picturebox_Click);
and check the Tag there
private void picturebox_Click(object sender, EventArgs e)
{
PictureBox pb = sender as PictureBox;
if (pb != null)
{
string s = pb.Tag
}
}
Upvotes: 0