Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access controls that is in the panel in c#

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'
like image 641
qulzam Avatar asked Aug 11 '09 13:08

qulzam


3 Answers

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

  1. PictureBox is followed by a period (.)
  2. 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);
like image 76
C. Ross Avatar answered Oct 11 '22 06:10

C. Ross


Try this:

foreach (Control p in panal.Controls)
{
    if (p is PictureBox)
    {
        p.Left = 50;
    }
}
like image 39
MusiGenesis Avatar answered Oct 11 '22 06:10

MusiGenesis


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;
  }
}
like image 34
David Basarab Avatar answered Oct 11 '22 06:10

David Basarab