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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In a for loop, i had to write var index=i; buttons[i].Click += (sender, e) => myClick(index); See stackoverflow.com/q/6439477
2
private void myClick(object sender, EventArgs e)
{
    int index = buttons.IndexOf(sender as Button);
}

2 Comments

This requires buttons to be a field, and linear search in the buttons array
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.

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.