我正在尝试移动位于Form1中的所有标签。我可以移动一个特定的标签,但如何循环和移动所有标签?感谢您的帮助和建议。
移动特定标签:
label1.Location = new Point(0, 0);
这不起作用:
Form1 f1 = new Form1();
for (int i = 0; i < f1.Controls.Count; i++)
{
f1.Controls[i].Location = new Point(0, 0);
{
答案 0 :(得分:2)
您可以遍历所有控件,但是您需要检查它是什么类型的控件,以查看它是否实际上是一个标签。以下代码应该有效,如果as
实际上不是标签,则labelControl
关键字将导致ctrl
为空
//Form1 f1 = new Form1(); // Removed, using this means you're calling from within the control you want to change already.
foreach (var ctrl in this.Controls)
{
var labelControl = ctrl as Label;
if (labelControl == null)
{
continue;
}
labelControl.Location = new Point(0, 0);
}
答案 1 :(得分:0)
您可以使用is限定符来确定控件是否确实是标签
//Form1 f1 = new Form1(); as pointed out this is not needed your are already on the right instance. doing new creates a new instance
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is Label){
Controls[i].Location = new Point(0, 0);
}
}
应该做的伎俩