C# loop through an array of given labels

2019-07-30 15:35发布

问题:

It's a bit difficult for me to describe, but this pseudo C# should explain what I'm trying to do.

There is a large number of labels on a windows form.

I'd like to change the text colour of some of those labels.

private void allBlackLabels()
{
    int[] lray = { 1, 2, 3, 5, 6 };
    foreach (int i in lray)
    {
        label[i].Forecolor = Color.Black;
    }            
}

I hope that explains what I am trying to do here.

Now it's obvious it won't work due to the label[i], but how would I get around this?

回答1:

It might not work, because your Labels aren't held in an array. The following code will work, considering you know the names of the label to be changed:

Label[] lray = { labelOne, labelDifferent, labelWhatElse };
foreach (Label label in lray)
{
    label.ForeColor = Color.Black;
}            


回答2:

That would work fine if you actually had an array of labels.

If you've only got lots of variables, like this:

private Label label1;
private Label label2;
private Label label3;
private Label label4;
private Label label5;

then it's harder. Options:

  • Change the code to use an array instead. Not as nice in the designer, but more logical
  • Use Controls.Find with each ID
  • Iterate over Controls to find all Label controls, regardless of name


回答3:

foreach (Control c in this.Controls)
{
    if (c is Label)
    {
        // do stuff
    }
}

That'll grab all of the form's child controls (provided this code is in the form's code-behind) and check to see if they're labels. Just do any manipulation you want in place of the comment.



回答4:

You could create the array yourself. This involves a bit of maintenance cost/risk each time your form changes though. Note: you probably want to put the array creation bit in a Form Loaded event, not a constructor, or at least, after the InitializeComponent call, so your controls are setup.

Or you could iterate on all the children of your Form (this.Controls from a Form method), mark your labels with a specific Tag, or get all Labels if that's your purpose here.

Please note that the first solution is probably much faster in runtime performance terms if you have many controls in your form.



回答5:

private void allBlackLabels()
{
    int[] lray = { 1, 2, 3, 5, 6 };
    foreach (int i = 0; i < lray.Length; i++)
    {
        ((Label)this.Controls["label" + i]).ForeColor = Color.Black;
    }            
}


回答6:

If you want to achieve this for all labels on the form then something like this may help:

foreach (Control control in this.Controls) {
     if (control is Label) {
         (control as Label).Forecolor = Color.Black;
     }
}

However if you only need to change a subset of all the labels then you need to either store the names or the indexes of the labels which need changing. This is because this.Controls has two indexers, an int32 and a string one. Thus you could try something like this

private void allBlackLabels()
{
    int[] lray = { 1, 2, 3, 5, 6 };
    foreach (int i in lray)
    {
         this.Controls[i].Forecolor = Color.Black;
    }            
}

It is defiantly worth noting however that the ordering in this.Controls will most likely not be as liniear looking as your lray array. Hope this helps



回答7:

Try some thing like this:

List<string> ListLabelNames = new List<string>() { /* Your label name list*/ };

foreach (Label TmpLabel in this.Controls.OfType<Label>())
{
    foreach (string strTmp in ListLabelNames)
    {
        if (String.Compare(TmpLabel.Name, strTmp, true) == 0)
            TmpLabel.ForeColor = System.Drawing.Color.Black;
    }
}

Hope this helps.



回答8:

I noticed that you excluded 4 from the "lray" array in your example. If you are looking to exclude one or more labels from being automatically updated by code (perhaps to highlight one among a group), try this.

    private void allBlackLabels()
    {    
        foreach (Control control in this.Controls)            
        {
            if (control is Label && control.Name != "label4")
            {
                (control as Label).Forecolor = Color.Black;
            }
        }
    }


回答9:

in pseudo c#:

List<String> controlsToChange =new List<String>{"lable1Name","lable2Name"};
foreach(Control control in form.Controls)
{
    if(control.GetType().Equals(typeof(Lable))
    {
         if( controlsToChange.Contains(control.Name)
         {
              control.Forecolor=Colour.Black;
         }
    }
}