0

I want to store a series (six to be precise) of Windows Forms labels in an array. There are six labels, which follow the naming convention orderLabel0, orderLabel1... orderLabel5.

I would like to store the pointers to the orderLabels in an array:

Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{                
    orderLabels[index] = orderLabel + [index]; //Error!
}

The code somehow needs to treat the string as variable name and store them as "labels" rather than string in the orderLabels array. In other words, when orderLabels[0] is accessed, I am actually accessing orderLabel0.

Research here and there have led me to dynamic, Reflection and Dictionary options. However, they all require me to specify the object names (correct me if I am wrong), and I am trying to follow the "Do Not Repeat" yourself rule by not having to specify the object six times.

Please advise, thank you.

5
  • create a hashmap... i find it very funny that if i google most of these questions exactly ill get a stack overflow question with the answer. stackoverflow.com/questions/1293549/string-to-variable-name Commented Aug 24, 2016 at 21:25
  • child controls are already stored in the parent container Controls property Commented Aug 24, 2016 at 21:27
  • Does orderLabel0 to orderLabel5 already exist on your form? Commented Aug 24, 2016 at 21:27
  • Hi Reza and Seany84, yes there are. Commented Aug 24, 2016 at 21:29
  • Take a look at this post. You can simply find them using their names. The name which you need to use in the loop is string.Format("orderLabel{0}", index). Commented Aug 24, 2016 at 21:30

1 Answer 1

2

You can use the Controls form variable to look up the control by name:

Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{                
    orderLabels[index] = Controls[string.Format("orderLabel{0}", index)] as Label;
}
Sign up to request clarification or add additional context in comments.

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.