[英]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 我在c#winforms中使用一个面板,并使用循环填充面板中没有图片框
For example, panel name is panal 例如,面板名称是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. 现在我想用另一种方法改变picturebox的位置。 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'
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 错别字是
The error is: 错误是:
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);
Try this: 尝试这个:
foreach (Control p in panal.Controls)
{
if (p is PictureBox)
{
p.Left = 50;
}
}
Next there might be some bugs in your for loop. 接下来你的for循环可能会有一些错误。
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;
}
}
Don't you want 你不想要吗?
panel.Controls
//^ this is an 'e'
instead of 代替
panal.Controls?
//^ this is an 'a'
在你的第二个块中,p.GetType == PictureBox之后的时间段是错误的(此处不需要句点)...就此而言,GetType是一个方法/函数而不是一个Property,所以它需要是p.GetType()
你最好将图片框变成表单本身的私有变量,这样你就可以用它做事情,而不必每次都通过面板的控件。
I think 我认为
foreach (PictureBox p in panel.Controls.OfType<PictureBox>())
{
p.Location = new Point(50, p.Location.Y);
}
could be solution too. 可能也是解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.