简体   繁体   中英

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

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.

Put the business logic that you want to execute in a separate method (eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM