0

It is possible to create something like that:

int[] array = new int[3]{1,2,3};
Button "btn"+array[0] = new Button();
2
  • in what scenario would you want to use this? Commented May 8, 2011 at 20:25
  • add dynamic controls to panel with unique names Commented May 8, 2011 at 20:27

3 Answers 3

4

You can easily create an array of Button instances, but you won't be able to access them by name at compile-time; since the name would be generated at runtime, you would have to store the keys at runtime as well.

The closest thing you could do is populate an implementation of IDictionary<string, Button>, like so:

int[] array = new int[3] { 1, 2, 3 };

IDictionary<string, Button> buttons = 
    array.ToDictionary(i => "btn" + i, i => new Button());

Of course, accessing the controls through the keys (i.e. btn1, btn2, btn3) is the problem you have to overcome (I assume you'd store these somewhere, and access them later).

Based on your comment, It should be noted that the names that you are referring to are not significant to the form or the framework, they are only significant to you. You don't have to use an IDictionary if you don't wish, it's just if you wish to do further work on them later (depending on your needs).

Sign up to request clarification or add additional context in comments.

Comments

2

This is not possible - you could use a dictionary instead:

var myButtons = new Dictionary<string,Button>();
myButtons.Add( "btn"+array[0], new Button());

var firstButton = myButtons["btn1"];

Comments

1

What you asked is not directly possible, but I think there is an answer for what you're actually looking for:

Suppose you've got any IEnumerable<int> like your own array:

Dictionary<int, Buttton> buttons = new Dictionary<int, Button>;
foreach (int key in array)
{
  Button b = new Button();
  b.Text = key.ToString();
  buttons.Add(key, b);
}

now you can easily use the buttons like this: buttons[1]

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.