开发者

How to know when a button is clicked in form1 but know in form2 C#

C#. Hello... I have 2 forms => Form1 with a button and Form2. I want to know how i can mannage the event of the button of开发者_Python百科 the Form2 in Form1. So when i make a click in form2 i want to know in form1 to do something


Form1 requires a reference to Form2. Then, you just hook up an event handler in Form1 to the button in Form2.

// code in form1 might look something like

public void SubscribeToEvents()
{
   // get Form2 reference
   var form2 = GetForm2Reference();
   form2.Button.Click += ButtonOnForm2EventHandler;
}

public void ButtonOnForm2EventHandler(object sender, EventHandlerArgs e)
{
   // some code
}


Form1 can subscribe to the events of Form2. You need a handle onto Form2 in Form1 but then you can simply write:

instanceOfForm2.Button.Click += handlerInForm1;


As stated by others but without making public controls or finding references if you already have them:

In form2 create a method to send other method to subscribe the button click:

   public void SubscribeToButton(EventHandler eh) {
       button1.Click += eh;
   }

in form1 subscribe to form2:

   form2.SubscribeToButton(this.f2_button_Click);

and have a method in it that will execute on click

   private void f2_button_Click(object sender, EventArgs e) {
   }

I actually written the wrong order, so please threat form1 as form2 and viceversa.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜