1

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
  • 1
    Why is it "obvious it wont work due to the label[i]"? Should we assume you don't currently have your labels conveniently available? Is the real question here "how can I get all the labels from a form, keyed by their name in the form label17?" ? Commented Oct 17, 2011 at 9:26

9 Answers 9

4

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;
}            
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect thank you! Why I was going down the route I was I will never know! Thank you sir.
1

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

Comments

1
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.

2 Comments

Personally I'd use LINQ there: foreach (Label label in this.Controls.OfType<Label>())
But that will change all labels and tripbrock wanted to change only some of them.
0

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.

2 Comments

If you give the labels the same name in the designer it'll create an array for you - no real chance of getting it wrong then. EDIT: Well, at least you used to be able to.
@KristianFenn Interesting. That may or may not cover the use cases of OP though. For instance, he might have two different sets of labels depending on some runtime property.
0
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;
    }            
}

Comments

0

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

1 Comment

Let's hope all the controls are directly on the outermost control/form, and not-nested...
0

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.

Comments

0

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

Comments

-1

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

6 Comments

But that will change all labels and tripbrock wanted to change only some of them.
@Fischermaen, really? or will it change only those which have entries in the controlsToChange list?
No it will change only the labels specified in the List.
@SamHolder: You're right. Sorry! If you have a List<Label> than you could save the test of the right type.
@Fischermaen indeed your are right, you could save the test. Can you remove the downvote perhaps?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.