Christine
Christine

Reputation: 238

Is combining strings to make up the name of a pre-existing Control possible?

I have a fair amount of Button controls that are dynamically created at runtime. The amount of these controls is user-determined, and they are given 'incremental' names.

For example, the buttons are arranged in a two dimensional 'table-like' format, and are named as such:

Name:(XAxisNo)(YAxisNo)
Box11
Box12
Box13

These are all public, and I want to edit them from a void that gets called by clicking another part of the interface.

Initially I (foolishly, in hindsight) thought that something like this could work:

for(int x = 1; x!= chunkCountX; x++)
{
     for(int y=1;y!= chunkCountY; y++)
     {
       ["Box" + x + y].BackgroundImage = presetImageVar;
     }

But that didn't work, so I tried something similar to this:

Button currentButton = new Button();
for(int x = 1; x!= chunkCountX; x++)
{
    for(int y=1;y!= chunkCountY; y++)
    {
        currentButton.Name = "Box" + x + y;
        currentButton.BackgroundImage = presetImageVar;
        currentButton.BackgroundImage = presetImageVar;
    }
}

My question is: Is it possible to build the name of an existing Control out of variables that I can then interface with the properties, or would it have to be done some other way?

Upvotes: 3

Views: 56

Answers (2)

Selman Genç
Selman Genç

Reputation: 101681

Instead of:

["Box" + x + y].BackgroundImage

Try:

this.Controls["Box" + x + y].BackgroundImage

You can access your Controls by it's name.Here, this represents your Form.If your buttons are direct child control of the Form, this should work.Otherwise you need to access control collection of your actual container instead of your Form.

for(int x = 1; x < chunkCountX; x++)
{
     for(int y=1; y < chunkCountY; y++)
     {
         string btnName = "Box" + x + y;
         if(this.Controls.ContainsKey(btnName)) 
                this.Controls[btnName].BackgroundImage = presetImageVar;
     }
}

Here is another solution with LINQ which gets all the buttons in nested controls that has the name starts with "Box" and change the BackgroundImage:

var buttons = this.Controls.OfType<Control>()
                   .SelectMany(x => x.Controls.OfType<Button>()
                                     .Where(x => x.Name.StartsWith("Box")));
foreach(var button in buttons)
      button.BackgroundImage = presetImageVar;

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

If all dynamically created buttons have name starting with Box and you want to update them all, then you can use LINQ to select such buttons and then update them in a loop:

var buttons = Controls.OfType<Button>().Where(b => b.Name.StartsWith("Box"));

foreach(var button in buttons)
    button.BackgroundImage = presetImageVar;

Upvotes: 1

Related Questions