繁体   English   中英

如何在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);
{

您可以遍历所有控件,但需要检查控件的类型以查看它是否实际上是标签。 下面的代码应该可以工作,如果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);
}

您可以使用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);
    }
}

应该可以

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM