Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#Winforms中以编程方式移动Form1中的所有标签_C#_Winforms_Label - Fatal编程技术网

如何在C#Winforms中以编程方式移动Form1中的所有标签

如何在C#Winforms中以编程方式移动Form1中的所有标签,c#,winforms,label,C#,Winforms,Label,我正在尝试移动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); { form1f1=newform1(); 对于(in

我正在尝试移动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);
{
form1f1=newform1();
对于(int i=0;i
您可以使用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);
    }
}
//Form1 f1=new Form1();如前所述,不需要这样做,因为您的实例已经正确。执行“新建”操作将创建一个新实例
for(int i=0;i

你可以循环所有控件,但你需要检查它是什么类型的控件,以查看它是否实际上是一个标签。下面的代码应该可以工作,
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);
}

谢谢你的回答,但我的问题不在if语句中,而是如何引用所有标签和更多标签。在你的问题中,你已经有了下一个的for。这也行。问题是你需要知道孩子是一个标签是或不是。该部分缺失,我只是完成了缺失的部分。如果你用你的cod行尝试我的代码e、 它可以工作?如果你修复了你的编译器错误,是的,它应该可以工作。你的closing}是一个open{,编译器不会喜欢那样。但是for next循环也可以。做一个'as Label'可以工作,首先通过'is'检查也可以。有多种方法可以实现你想要的。我没有任何编译器错误,“这不工作”(从我的帖子中)=什么都不做。你试过了吗?我不知道为什么对我来说不起作用。我创建了一个新的winforms应用程序并在那里尝试了它,而不是Form1 f1=new Form1(),尽管我在表单本身中使用了
foreach(在这个.Controls中使用var ctrl)
相反。当你说它不起作用时,你能更具体地说,你得到了什么错误/行为吗?好的,现在foreach(在这个.Controls中是var-ctrl)而不是foreach(在f1.Controls中是var-ctrl)起作用了!:-)谢谢!没问题。=)我猜您是在表单本身中调用此代码?如果是这种情况,那么当您调用
Form f1=new Form1()时
您实际上是在创建表单的另一个实例,然后移动该实例上的标签,但是因为显示的表单不是该表单,所以您看不到任何更改。在表单代码中使用此
本身指的是当前实例化的表单。是的,这是问题的本质。我没有看到,因为未提供方法名称。