如何在 C# 中调用事件方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2152429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I call an event method in C#?
提问by Moon
When I create buttons in C#, it creates private void button_Click(object sender, EventArgs e)
method as well.
当我在 C# 中创建按钮时,它private void button_Click(object sender, EventArgs e)
也会创建方法。
How do I call button1_click
method from button2_click
?
Is it possible?
我如何button1_click
从调用方法button2_click
?
是否可以?
I am working with Windows Forms.
我正在使用 Windows 窗体。
采纳答案by SwDevMan81
// No "sender" or event args
public void button2_click(object sender, EventArgs e)
{
button1_click(null, null);
}
or
或者
// Button2's the sender and event args
public void button2_click(object sender, EventArgs e)
{
button1_click(sender, e);
}
or as Joel pointed out:
或者正如乔尔指出的那样:
// Button1's the sender and Button2's event args
public void button2_click(object sender, EventArgs e)
{
button1_click(this.button1, e);
}
回答by Tj Kellie
You can wire up the button events in the ASPX file code.
您可以在 ASPX 文件代码中连接按钮事件。
The button tag will wire the events like this:
按钮标签将像这样连接事件:
<asp:Button Text="Button1" OnClick="Event_handler_name1" />
<asp:Button Text="Button2" OnClick="Event_handler_name1" />
Just wire the OnClick= to your handler method for button1
只需将 OnClick= 连接到 button1 的处理程序方法
回答by Josh
You don't mention whether this is Windows Forms, ASP.NET, or WPF. If this is Windows Forms, another suggestion would be to use the button2.PerformClick() method. I find this to be "cleaner" since you are not directly invoking the event handler.
您没有提到这是 Windows 窗体、ASP.NET 还是 WPF。如果这是 Windows 窗体,另一个建议是使用 button2。PerformClick() 方法。我发现这更“干净”,因为您没有直接调用事件处理程序。
回答by Juliet
How do I call button1_click method from button2_click? Is it possible?
如何从 button2_click 调用 button1_click 方法?是否可以?
Its wholly possible to invoke the button's click event, but its a bad practice. Move the code from your button into a separate method. For example:
完全可以调用按钮的点击事件,但这是一种不好的做法。将按钮中的代码移动到单独的方法中。例如:
protected void btnDelete_OnClick(object sender, EventArgs e)
{
DeleteItem();
}
private void DeleteItem()
{
// your code here
}
This strategy makes it easy for you to call your code directly without having to invoke any event handlers. Additionally, if you need to pull your code out of your code behind and into a separate class or DLL, you're already two steps ahead of yourself.
这种策略使您可以轻松地直接调用代码,而无需调用任何事件处理程序。此外,如果您需要将代码从后面的代码中提取出来并放入一个单独的类或 DLL 中,那么您已经领先了两步。
回答by Nakul Chaudhary
You can bind same handler for the event of both buttons
您可以为两个按钮的事件绑定相同的处理程序