Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I am in the middle of a project and need to add functions into a array of buttons so each button will run that function upon click. I have created the array which also uses a struct for all properties during initialising. I cannot hard code the functions because a previous function sets the size and order of the button array. I have looked through the net and can't seem to find a specific answer that is relevant. I am fairly new to programming (in my 2nd year) so sorry if my terminology is fresh from college. Any help/advice would be greatly appreciated, thank you.

share|improve this question

3 Answers 3

Write your common event handler as follow with proper parameters.

private void MyCommonFunctionForAllButtons(object sender, System.EventArgs e)
{
    //Write the logic you want to execute once any button is pressed.
}

Assign the same event handler for all the buttons in your array.

foreach( Button button in buttonArray ) 
{
    button.Click += MyCommonFunctionForAllButtons;
}
share|improve this answer

Something like this I guess:

Button[] buttons = ... ;
for (int i=0; i < buttons.Length; i++)
{
    Button b = buttons[i];
    b.TabIndex = i;
      ... set other properties here, as desired....
    b.Click += new System.EventHandler(clickHandler[i]);
}

If this isn't what you were thinking, maybe you could show some code to illustrate what you want.

share|improve this answer

You need to loop through a list of buttons and assign an onclick handler?

foreach( Button button in buttons ) {
    button.Click += methodName;
}

Or was there something more to your question?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.