Search code examples
c#winformsevent-handlingbindcontrol-array

How to bind a function to Click event of each control in an array of controls in C#


When you create an array of controls in C#, how can you bind a function that receives the index of the clicked button to their click event?

Here's some code solely for better understanding. Somewhere on top of the code you define the buttons:

Button [] buttons = new Button[100];

The standard Click event of them looks like this:

private void myClick(object sender, EventArgs e)
{

}

And normally you bind it this way:

for (int i = 0; i < 100; i++)
    buttons[i].Click += myClick;

But I want the event handler to be in this form:

private void myClick(int Index)
{

}

How should I bind click events to the above function with / without interim functions?

I thought about using delegates, Func<T, TResult> notation, or somehow pass a custom EventArgs which contains the Index of the clicked button; but I wasn't successful due to lack of enough C# knowledge.

If any of you are going to suggest saving the index of each control in its Tag: Yes it was possible but I don't wanna use it for some reason, since if you have a class which throws some events but doesn't have a Tag property or something, this way is useless.


Solution

  • int index = i;    
    buttons[index].Click += (sender, e) => myClick(index);
    

    As posted in the comment below, using 'i' will use the same variable for all controls due to it's scope. It's therefore necessary to create a new variable in the same scope as the lambda expression.