0

So i have 2 forms: Form1 and Form2

In Form1 i have this code:

pubilc class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Button1_Click(object sender, EventArgs e)
    {
        Form2 newForm = new Form2(); //Here i want to pass MyFunction
    }

    public void MyFunction()
    {
        MessageBox.Show("This is passed function from " + this.Text);
    }
}

And in Form2 i have this:

public class Form2 : Form
{
    public Form2() //Here i want to receive Form1.MyFunction
    {
        InitializeComponent();
        this.Button1.Click += new System.EventHandler(passedFunction);
    }
}

In code above you can get my point. Having form with controls to which i would assign Eventhandlers with passed function while creating that form.

I haven't tried anything since i do not have idea how to pass method to form.

Aleksa Ristic
  • 2,394
  • 3
  • 23
  • 54
  • Possible solution : https://stackoverflow.com/questions/4247807/passing-variable-between-winforms https://stackoverflow.com/questions/4176682/access-of-public-method-between-forms – Anoop J May 31 '18 at 06:18

1 Answers1

3

Try this:

public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Button1_Click(object sender, EventArgs e)
    {
        Form2 newForm = new Form2(MyFunction); //Here i want to pass MyFunction
    }

    public void MyFunction(object sender, EventArgs e)
    {
        MessageBox.Show("This is passed function from " + this.Text);
    }
}

public class Form2 : Form
{
    public Form2(EventHandler passedFunction) //Here i want to receive Form1.MyFunction
    {
        InitializeComponent();
        this.Button1.Click += passedFunction;
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172