Mohan Krishna
Mohan Krishna

Reputation: 31

Selecting a button using its name among buttons that were created dynamically in c#

I'm creating buttons dynamically. How can I select a specific button using its name (ex: in the following code using "i" ) from remaining part of the code.

for(int i = 0; i < 5; i++)
{
    button b = new button();
    b.name = i.ToString();
}

Upvotes: 2

Views: 2219

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You have to place your button somewhere:

  for (int i = 0; i < 5; i++) {
    // Mind the case: Button, not button
    Button b = new Button();
    // // Mind the case: Name, not name
    b.Name = i.ToString();

    //TODO: place your buttons somewhere:
    // on a panel
    //   myPanel.Controls.Add(b);
    // on a form
    //   this.Controls.Add(b);
    // etc.

    //TODO: it seems, that you want to add Click event, something like
    //  b.Click += MyButtonClick;  
  }

then you can just query appropriate Controls for the Button:

  Button b = myPanel.Controls["1"] as Button;

  if (b != null) {
    // The Button is found ...
  } 

Upvotes: 1

Tinwor
Tinwor

Reputation: 7973

A simpler solution is search the button in the Controls collection.

Button btn = (Button) this.Controls["nameButton"];
//...DO Something

The problem of this solution is that if there isn't a button with the nameButton the JIT will throw an exception. If you want prevent this you must insert the code in a try catch block or, if you prefer, you can use Sergey Berezovskiy solution(he uses Linq and I think it's more clear)

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

First - its not enough to just create buttons. You need to add them to some control:

for(int i = 0; i < 5; i++)
{
    Button button = new Button();
    button.Name = String.Format("button{0}", i); // use better names
    // subscribe to Click event otherwise button is useless
    button.Click = Button_Click;
    Controls.Add(button); // add to form's controls
}

Now you can search child controls of buttons container for some specific button:

var button = Controls.OfType<Button>().FirstOrDefault(b => b.Name == "button2");

NOTE: If you'll use buttonN name pattern then make sure you don't have other buttons with same names, because this pattern is used by VS designer.

UPDATE: If you will use same event handler for all dynamic buttons Click event (actually you should), then you can easily get button which raised even in event handler:

private void Button_Click(object sender, EventArgs e)
{
    // that's the button which was clicked
    Button button = (Button)sender;
    // use it
}

Upvotes: 2

Dennis_E
Dennis_E

Reputation: 8894

You could just put them in a Button[] or you could iterate over the Controls collection of your Form.

Upvotes: -1

Related Questions