如何使菜单项单击事件调用方法 [英] how to make a menu item click event invoke a method
问题描述
大家好,
我正在构建一个桌面数据库应用程序。我希望菜单项的单击事件调用从数据库中获取数据的方法。以下是代码行:
Hello guys,
I am building a desktop database application. I want the menu items' click events to invoke methods that would fetch data from the the database. Here is the line of code:
//viewAllStaff.Click += new System.EventHandler(pdt.viewAllStaffMethod());
它提示我错误:方法名称预期。
请帮助。我是新手。
It prompt me that " error: method name expected".
Kindly help. I am a novice.
推荐答案
添加事件处理程序时,您需要提供方法名称,仅此而已。您的代码在方法名称后面有括号,就像您尝试调用该方法一样。将其更改为:
When adding the event handler, you are expected to supply a method name, nothing more. Your code has brackets after the method name, as if you are trying to call the method. Change it to:
viewAllStaff.Click += new System.EventHandler(pdt.viewAllStaffMethod);
编辑:
处理事件的方法不能只是任何旧方法。它需要遵循.NET的特定模式才能在事件发生时调用它。对于菜单项的单击事件,该模式为:
1.方法的返回类型必须为 void
。
2.该方法必须接受两个参数:对象
名为 sender
和 EventArgs
名为 e
。
因此,方法声明必须是:
The method handling the event cannot be just any old method. It needs to follow a specific pattern for .NET to be able to call it when the event happens. In the case of a menu item's click event, that pattern is:
1. The method's return type must be void
.
2. The method must accept two parameters: an object
named sender
and an EventArgs
named e
.
As such, the method declaration must be:
public void viewAllStaffMethod(object sender, EventArgs e)
这篇关于如何使菜单项单击事件调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!