问题
I use a panel in c# winforms and fill the panel with the no of picture box using loop
For example, panel name is panal
foreach (string s in fileNames)
{
PictureBox pbox = new new PictureBox();
pBox.Image = Image.FromFile(s);
pbox.Location = new point(10,15);
.
.
.
.
this.panal.Controls.Add(pBox);
}
now I want to change the location of picturebox in another method. The problem is that how can now I access the pictureboxes so that I change the location of them. I try to use the following but it is not the success.
foreach (Control p in panal.Controls)
if (p.GetType == PictureBox)
p.Location.X = 50;
But there is an error. The error is:
System.Windows.Forms.PictureBox' is a 'type' but is used like a 'variable'
回答1:
There appear to be some typos in this section (and possibly a real error).
foreach (Control p in panal.Controls)
if (p.GetType == PictureBox.)
p.Location.X = 50;
The typos are
- PictureBox is followed by a period (.)
- GetType is missing the parens (so it isn't called).
The error is:
- You can't compare the type of p to PictureBox, you need to compare it to the type of PictureBox.
This should be:
foreach (Control p in panal.Controls)
if (p.GetType() == typeof(PictureBox))
p.Location = new Point(50, p.Location.Y);
Or simply:
foreach (Control p in panal.Controls)
if (p is PictureBox)
p.Location = new Point(50, p.Location.Y);
回答2:
Try this:
foreach (Control p in panal.Controls)
{
if (p is PictureBox)
{
p.Left = 50;
}
}
回答3:
Next there might be some bugs in your for loop.
foreach (Control p in panel.Controls)
{
if (p is PictureBox) // Use the keyword is to see if P is type of Picturebox
{
p.Location.X = 50;
}
}
回答4:
I think
foreach (PictureBox p in panel.Controls.OfType<PictureBox>())
{
p.Location = new Point(50, p.Location.Y);
}
could be solution too.
回答5:
Don't you want
panel.Controls
//^ this is an 'e'
instead of
panal.Controls?
//^ this is an 'a'
回答6:
In your second block the period after p.GetType == PictureBox is wrong (no period required here)... for that matter, GetType is a method/function not a Property so it needs to be p.GetType()
回答7:
You would be better off making the picturebox a private variable of the form itself, so that you could do things with it without having to step though the panel's controls every time.
来源:https://stackoverflow.com/questions/1260296/how-to-access-controls-that-is-in-the-panel-in-c-sharp