0

I have to call a form2's click event on form1. There is many example with "call function from another form" But there is not had when form is already opened. How do I click form2's button on form1?

//form1 code
 private void button1_Click(object sender, EventArgs e)
{
           var _callForm = new form2(); //this open's new form but it was already open.
           _callForm.StartPosition = FormStartPosition.CenterScreen;
           _callForm.textbox1 = _sampletext;
           _callForm.checkbox1.Checked = true;            
           _callForm.form2button1.PerformClick();
           _callForm.ShowDialog();       
}

//form1 and form2 are still opened.

//form2 code. 
//checkbox1,form2button1,textbox1 These are public in designer code 
 private void form2button1_Click(object sender, EventArgs e)
{
//do something     
}
Grant
  • 13
  • 6
  • If you make the call `public` rather than `private`, you can call the click handler. You can't just _call_ an `event` – Flydog57 Apr 16 '21 at 05:25
  • Don't throw away the reference to _callform, you need it to call that, or alternatively put a static member – Martheen Apr 16 '21 at 05:27

1 Answers1

0

You shouldn't create a new object of your Form1 since it's already opened You can do this on your second form:

Form1 firstForm;
public Form2(Form1 first)
{
    InitializeComponent();
    firstForm = first;
}

private void form2button1_Click(object sender, EventArgs e)
{
    firstForm.MethodYouWantToCallFromForm1(); //The method should be public
}

And on the first form, you need to call the constructor of the Form2 that has a parameter

public Form1()
{
    InitializeComponent();
}
private void form1button1_Click(object sender, EventArgs e)
{
    Form2 form = new Form2(this);
    form.Show();
}
Andrei Solero
  • 802
  • 1
  • 4
  • 12