Gewoo
Gewoo

Reputation: 457

Create a variable for a button from a string

so I would like to create a button from a string. I know how to access a button by a string if it is already created but that isn't the case atm.

Like this: Button "myButton" = new Button();

But of course that does not work, is this possible to do?

Upvotes: 1

Views: 3069

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

Assuming you are using ControlCollection.Find to find your controls by a string, then note the MSDN entry:

Searches for controls by their Name property and builds an array of all the controls that match.

It doesn't care what (if any) variable name the button was assigned to (nor can it know or use it in any useful way), it cares only about the Name property of your button. So you could do something like this:

var IDontCareWhatThisIsCalled = new Button()
{
    Name = "myButton"
};
someForm.Controls.Add(IDontCareWhatThisIsCalled);

And then:

var thatButton = someForm.Controls.Find("myButton");

However, if you have a bunch of buttons that you need to be able to look up by name, then the best option is probably to put them in a Dictionary<string,Button>:

Dictionary<string,Button> buttonDictionary = new Dictionary<string,Button>();
// ....
var b = new Button();
buttonDictionary["myButton"] = b;
someForm.Controls.Add(b);
// ...
// To retrieve later:
var thatButton = buttonDictionary["myButton"];   // Note if the key doesn't exist, it will
                                                 // throw an exception - so check first

Upvotes: 2

Related Questions