如何访问c#中面板中的控件

qul*_*zam 6 c# desktop-application winforms

我在c#winforms中使用一个面板,并使用循环填充面板中没有图片框

例如,面板名称是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);
}
Run Code Online (Sandbox Code Playgroud)

现在我想用另一种方法改变picturebox的位置.问题是,现在我怎样才能访问图片框,以便我改变它们的位置.我尝试使用以下但不是成功.

foreach (Control p in panal.Controls)
                if (p.GetType == PictureBox)
                   p.Location.X = 50;
Run Code Online (Sandbox Code Playgroud)

但是有一个错误.错误是:

System.Windows.Forms.PictureBox' is a 'type' but is used like a 'variable'
Run Code Online (Sandbox Code Playgroud)

C. *_*oss 21

本节中似乎存在一些拼写错误(可能是真正的错误).

foreach (Control p in panal.Controls)
                if (p.GetType == PictureBox.)
                   p.Location.X = 50;
Run Code Online (Sandbox Code Playgroud)

错别字是

  1. PictureBox后跟一段时间(.)
  2. GetType缺少parens(因此不会调用它).

错误是:

  • 你不能将p的类型与PictureBox进行比较,你需要将它与PictureBox的类型进行比较.

这应该是:

foreach (Control p in panal.Controls)
   if (p.GetType() == typeof(PictureBox))
      p.Location = new Point(50, p.Location.Y);
Run Code Online (Sandbox Code Playgroud)

或者干脆:

foreach (Control p in panal.Controls)
   if (p is PictureBox)
      p.Location = new Point(50, p.Location.Y);
Run Code Online (Sandbox Code Playgroud)