Calling another forms method/function


Frequently when writing winforms applications, one needs to call a method/function in another form. This is very handy for instance, if you want to refresh the other form after changing values in a database.

After trying to solve this using delegates, I came across this eloquent solution.

Create two Winforms, F1 and F2 with a button in each.

In Form 1

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void MyMessage()
        {
            MessageBox.Show("Hello from Form 1");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2(this);
            form2.ShowDialog(this);
        }
    }
}

In Form 2

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        Form1 form1;

        public Form2(Form1 form1)
        {
            InitializeComponent();
            this.form1 = form1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.form1.MyMessage();
        }
    }
}

 

The instance of form 1 is passed to the second form using the this keyword. Ultimately what is passed is just a reference (pointer) to the form object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s