什么是调用一个按钮的Click事件的正确方法? [英] What is the right way to invoke a button's click event?

查看:164
本文介绍了什么是调用一个按钮的Click事件的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面: http://msdn.microsoft .COM / EN-US /库/ hkkb40tf(v = VS.90)的.aspx ,它说,从另一个按钮调用按钮的点击事件,你可以/应该这样来做:

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();

不过,在我的情况(2003年VS NET 1.1),这并不编译(当然,上面的链接指定了VS 2008,但它不会有一个链接,为以前版本的相关信息,如MSDN经常做)。

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).

这编译:

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.

推荐答案

将要在一个单独的方法来执行业务逻辑(如DoSave就会()),然后你的事件处理程序既可以只调用内部方法,而不是直接调用对方。

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.

这篇关于什么是调用一个按钮的Click事件的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆