What is the right way to invoke a button's click event?

扶醉桌前 提交于 2020-01-03 05:14:23

问题


Here: http://msdn.microsoft.com/en-us/library/hkkb40tf(v=VS.90).aspx, it says that, to call a button's click event from another button, you can/should do it this way:

button1.PerformClick();

However, in my situation (VS 2003. NET 1.1), this doesn't compile (admittedly, the link above specifies VS 2008, but it does not have a link to the pertinent info for prior versions, as msdn often does).

This compiles:

private void btnPrint_Click(object sender, System.EventArgs args)
{
    if (this.recordChanged)
    {
        //btnSave.Click();
        btnSave_Click(sender, args);
    }
    . . .

...but I don't know if it's THE way to do it.


回答1:


Put the business logic that you want to execute in a separate method (e.g. DoSave()), and then your event handlers can both just call that internal method rather than calling each other directly.

"Faking" events by calling the event handler methods directly is ugly and can lead to bugs (any programmer modifying the event handler in future may be unaware that it could be called under different conditions than expected/documented, which could cause the print option to behave strangely or even crash when it tries to do a save operation)

Also there is a good chance that you may want to cause a save operation from somewhere else in future - so it's always a very good idea to keep the business logic separate from the use interface that activates it.




回答2:


I would do btnSave.Click(sender, args);. Here's the page on MSDN: http://msdn.microsoft.com/en-us/library/aa645739(v=VS.71).aspx



来源:https://stackoverflow.com/questions/14987662/what-is-the-right-way-to-invoke-a-buttons-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!