1

To create Button and its click event in run time I use:

Button b = new Button();
b.Name = "btn1";
b.Click += btn1_Click;

But now I have an array of Buttons to create in run time; how to set each button's event - I cannot interpolate because it's not a string.

Button[] b = new Button(Count);
for (int i=0; i < Count; i++)
{
  b[i] = new Button();
  b[i].Name = "btn" + i;
  b[i].Click += ??????
}

what should I do for "?????"

3 Answers 3

5

Option 1:

You can pass an lambda function, and create the handler based on the buttons index in the array like this:

for (int i=0; i < Count; i++)
{
   b[i] = new Button();
   b[i].Name = "btn" + i;
   b[i].Click += (sender, args) => 
   {
     // your code
   }
}

Option 2:

You can pass an anonymus delegate:

b[i].Click += delegate (sender, args) {
         // your code
};

Option 3:

You can specify a handler function:

b[i].Click += YourHandlerFunction
// ....

// The handler signature also has to have the correct signature
void YourHandlerFunction(object sender, ButtonEventArgs  args) 
{
    // your code
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can bind all buttons to the same event, so put the line like b[i].Click += button_Click;.

Then inside the button_Click event you can differentiate between the buttons, and take the proper actions.

For example:

public void button_Click(object sender, ButtonEventArgs e)
{
  if( sender == b[0] )
  {
    //do what is appropriate for the first button
  }
  ...
}

1 Comment

thanks, I tried and found this to be the better answer. Without the "sender == b[o]" and if I put array in the lamda function, it will throw an exception because the array is null when it is called.
1

It depends on what you want to do! If you want to have the same method called for all clicks, do this:

Button[] b = new Button[Count];

for (int i=0; i < Count; i++)
{
    b[i] = new Button();
    b[i].Name = "btn" + i;
    b[i].Click += OnClick
}

private void OnClick(object sender, RoutedEventArgs e)
{
      // do something
} 

If you want to do something different for each button, e.g. depending on the index, you can do something like this:

Button[] b = new Button[Count];

for (int i=0; i < Count; i++)
{
    b[i] = new Button();
    b[i].Name = "btn" + i;
    b[i].Click += (s, e) => { /*do something*/ };
}

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.