Alex Rivera | Logout

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

Asked 2010-11-05T22:49:55.557
11

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:

  1. how do i declare a control public?
  2. how do i pass the correct events into button_click? it takes two parameters - how do i pass them,?
Edit
Report

3 Answers

17

Why not create a public method in a shared class that both click events execute.

answered 2010-11-05T22:53:49.840
7

It's possible to make a control in a Form public, but not recommended, you can do the following:

1) Declare a new event in the first form (form1) ButtonFirstFormClicked

public event EventHandler ButtonFirstFormClicked;

and trigger this event in the Button.Click event handler

void button_Clicked(object sender, EventArgs e)
{

    // if you're working with c# 6.0 or greater
    ButtonFirstFormClicked?.Invoke(sender, e);

    // if you're not then comment the above method and uncomment the below
    //if (ButtonFirstFormClicked!= null)
    //     ButtonFirstFormClicked(sender, e);
}  

2) In the second form (form2) subscribe the event

form1.ButtonFirstFormClicked += (s, e)
{
 // put your code here...
} 

Good luck!

answered 2010-11-05T23:14:05.617
3

You can use internal as your modifier, so you can easily access the click event.

for example you have a click event in form1. instead of making it private, public or protected. put it as internal this way you can easily access the method in other classes. But the internal modifier is only accessible within the current package.

Form1

internal passobj;
internal passeargs;

internal void button1_Click(object obj, EventArgs e)
{
 this.passobj = obj;
 this.passeargs = e;

 MessageBox.Show("Clicked!")
}

Form2

private void button1_Click(object obj, EventArgs e)
{

   Form1 f1 = new Form1();
   f1.button1_Click(f1.passobj, f1.passeargs);
}
answered 2010-11-06T06:08:25.513

Your Answer