Search code examples
c#visual-studiobuttoncompact-frameworkwindows-ce

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.


Solution

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