0

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.

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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?

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.