0

Is there a way that I could access a label with variable parameters? For example, I have a list of labels (lbl00, lbl01, lbl02, lbl10, lbl11, lbl12) and need to be able to access them programmatically to change the background color. In the example below, strLabel = "lbl01", which would correspond to the correct object in my form, but this cannot be passed as a string. Is there any way I could make this work?

Thanks!

        private void btnTest_Click(object sender, EventArgs e)
        {
            TestHilight("0", "1");
        }

        public void TestHilight(string x, string y)
        {
            String strLabel = "lbl" + x + y;
            strLabel.BackColor = System.Drawing.Color.Green;
        }
1
  • Use List<Label> or Dictionary<string,Label> Commented Apr 14, 2015 at 18:21

2 Answers 2

4

It is better if you keep track of your Labels in memory, but if you want to find a Label or a control based on Name then you can use Control.Find method:

var control = this.Controls.Find(strLabel, true); //pass "lbl" + x + y;
if(control != null && control.OfType<Label>().Any())
{
   //label found
   Label label = control.OfType<Label>().First() as Label;
   label.BackColor = System.Drawing.Color.Green;
}

You can shorten your code like:

public void TestHilight(string x, string y)
{
    var matchedLabel = Controls.Find("lbl" + x + y, true).OfType<Label>().FirstOrDefault();
    if (matchedLabel != null)
    {
        //label found
        matchedLabel.BackColor = System.Drawing.Color.Green;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, this worked! Thanks so much! I'll accept this answer as soon as I can! Can you elaborate a bit what you mean by keeping track of labels in memory?
@1337Atreyu, it looks like you are adding your labels dynamically on the form. You can keep track of your labels in a Dictionary<string,Label>, where your key would be label name and the value would be the actual label. In that way you could search for label easily. But it all depends on your requirement
0

You can either maintain a reference to label controls in a Dictionary where the key would be the string e.g. lbl01 and when you need to set the BackColor, find the corresponding label from the Dictionary and set its property.

Alternatively, you can search for the control by its name and set its BackColor property

Comments

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.