简体   繁体   中英

How do I check which button is being clicked? Visual Studio C#

I'm working with 70 buttons in my application, so I was thinking that instead of making different button1_Click, button2_Click... button70_Click events, I would just make one. The problem is that I don't know how to check what is the current button that is being clicked, since whenever I click a button I want its color to change.

Cast the sender parameter of your event handler to Button

Button ClickedButton = (Button)sender;

That is the button that raised the event.

You would use it in the handler you assign to each button's click event, eg

public form1() 
{
        //You probably do this in a loop over all your buttons
        button1.Click += MyButtonClickHandler;
}

private void MyButtonClickHandler(object sender, EventArgs e)
{
    Button ClickedButton = (Button)sender;
    ClickedButton.ForeColor = Color.Red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM