1

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.

Hossein
  • 4,097
  • 2
  • 24
  • 46

2 Answers2

6
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.

Bas
  • 26,772
  • 8
  • 53
  • 86
  • 1
    In a for loop, i had to write `var index=i; buttons[i].Click += (sender, e) => myClick(index);` See http://stackoverflow.com/q/6439477/ – Hossein Jun 22 '11 at 12:22
2
private void myClick(object sender, EventArgs e)
{
    int index = buttons.IndexOf(sender as Button);
}
DanielB
  • 19,910
  • 2
  • 44
  • 50
  • This requires buttons to be a field, and linear search in the buttons array – Bas Jun 22 '11 at 11:20
  • I'am aware of that, and I voted up your answer, because I like them. But at all, I would not miss the `EventArgs` in a handler. May be on further development, its required to interact with them. – DanielB Jun 22 '11 at 11:22