Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# User-controls UI
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:
 
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
Posted 14-Oct-12 2:13am
Edited 14-Oct-12 2:46am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Add a List to you UserControl:
private List<PictureBox> Pictures = new List<PictureBox>();
 
Then when you add it to the controls list, you also add it to the Pictures:
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:
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!)
  Permalink  
Comments
OriginalGriff at 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)

  Print Answers RSS
0 OriginalGriff 390
1 Jochen Arndt 150
2 Richard MacCutchan 135
3 DamithSL 95
4 Garth J Lancaster 90
0 OriginalGriff 6,045
1 DamithSL 4,601
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,260


Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 14 Oct 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100