C# Sending buttonclicks to same Object
I have a lot of buttons in my project. To make the program I shorter need to get every click of a button to the开发者_JS百科 same "Button_click" method. Is this possible?
Thanks
Just use the same event handler for all the buttons. In code, this would be:
button1.Click += HandleButtonClick;
button2.Click += HandleButtonClick;
etc
It should be possible to do in the designer too.
If these are buttons in different forms, you'll need to either have a static handler method somewhere, or each form will need a reference to whatever class has the handler method. You may well need to add these handlers in code, rather than using the designer.
Yes - it's perfectly possible.
You don't say whether you're WinForms or WPF but the basic way is to create a private method that's the handler and then call that from each button handler:
private void ButtonHandler(some arguments)
{
}
private void OnButton1Click(object sender, EventArgs e)
{
ButtonHandler(some arguments);
}
However, you can just subscribe the same handler to each button's click event:
Button1.Click += ButtonHandler;
Button2.Click += ButtonHandler;
Or set these from the designer - just pick the existing method from the drop-down list rather than creating a new handler.
With WPF you can quite easily bind each button click to the same handler in XAML:
<Button x:Name="Button1" Click="ButtonHandler" ... />
<Button x:Name="Button2" Click="ButtonHandler" ... />
Again the designer gives you the choice of selecting an existing handler as well as creating a new one.
Yes, it's possible, just select the method you need in your Events tab of Properties Window designer (you can show it from the main menu: View -> Properties Window):
Or do it manually in <Formname>.Designer.cs
file:
this.button1.Click += new System.EventHandler(this.button1_Click);
//...
this.button2.Click += new System.EventHandler(this.button1_Click);
Also, if you want to perform slightly different actions depenging of which button was pressed and still only use one method, use sender
argument. Its value will always be a reference to the button that was clicked, so you can do some logic by looking at button's Name
or Tag
properties:
private void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
switch((int)btn.Tag) {
case 1:
// action 1
break;
case 2:
// action 2
break;
}
}
Still, you should be careful with this and see if it really gives you any benefits to share an event handler instead of creating separate handlers for different buttons.
精彩评论