Is it possible to trigger a click event from another form?

前端 未结 5 884
北荒
北荒 2020-12-30 07:38

I need to run the code of a button that is on another form. is it possible to do it from a different form? if you say that it is possible by declaring it public then:

<
5条回答
  •  醉酒成梦
    2020-12-30 08:34

    In the form where the code is (firstForm) you will need to make the procedure public and avaliable to the secondary form where the secondary button is (btnMyButton). Once you have accomplished this you can hook up the click event hander of the secondary button to the code in the 1st form as follows.

    Secondarily as stated above by Dustin you could opt to move this code into a separate class and then simply reference the method handler with as many events as you need.

    Either way will work but I agree that if you want to follow good design you should have a separation of concerns as it relates to business logic (code) and presentation layer (ie forms with buttons)

    //button in 2nd form

    btnMyButton.Click += new EventHandler(firstForm.MethodThatHasCodeToRun);
    

    Hope this helps,

    Enjoy!

提交回复
热议问题