如何在 C# Winforms 中以编程方式移动 Form1 中的所有标签
How to move all labels in Form1 programmatically in C# Winforms
我正在尝试移动 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);
{
您可以使用 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);
}
}
应该可以解决问题
您可以遍历所有控件,但您需要检查它是什么类型的控件,以查看它是否真的是一个标签。下面的代码应该有效,如果 ctrl
实际上不是标签
,as
关键字将导致 labelControl
为 null
//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);
}
我正在尝试移动 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);
{
您可以使用 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);
}
}
应该可以解决问题
您可以遍历所有控件,但您需要检查它是什么类型的控件,以查看它是否真的是一个标签。下面的代码应该有效,如果 ctrl
实际上不是标签
as
关键字将导致 labelControl
为 null
//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);
}