简体   繁体   中英

How to move all labels in Form1 programmatically in C# Winforms

I am trying to move all the labels located in Form1. I can move a specific label, but how to loop and move all labels? Thank you for any help and advise.

Move a specific label:

label1.Location = new Point(0, 0);

This wont work:

Form1 f1 = new Form1();
for (int i = 0; i < f1.Controls.Count; i++)
{
    f1.Controls[i].Location = new Point(0, 0);
{

You can loop through all of the controls but you need to check what type of control it is in order to see if it is actually a label. The code below should work, the as keyword will result in labelControl being null if ctrl isn't actually a label

//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);
}

You can use the is qualifier to find out if the control is indeed a label

//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);
    }
}

should do the trick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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