Hi all,

I tried searching for my problem but i fear my keywords and problem is to generic. Apologies if this has been answered before.

OK, so I'm coding a Windows Forms app using C# in VS2008. It one of my first few applications and I'm struggling calling methods contained in my main form parent with the name main. I simply want a button click in a child form to execute a method in the parent. I' cant seem to do this .

Here is a method in my main.cs for demonstration purposes. (main.cs is instantiated from the default program.cs created by VS2008 using Application.Run(new main()); )

public void test()
{
    MessageBox.Show("test called");
}

My problem is that from a child form I can't seem to go main.test(). I'm guessing its because main isnt the instance, its the class. How would i go about getting a handle on main?

Thanks you for your time

Kez

Add eventhander in constructor of child form like this, Eventhandler must be introduced as public. In example I will use form named Main as main form.

public Form2()
        {
            InitializeComponent();
            button1.Click+=new EventHandler(((Main)Application.OpenForms["Main"]).button1_Click);
        }

Thank you for your answer. Its not so much the button click i'm interested in. Put simply i need to know how to call a method in the parent form from the child form

Kez

You need some way to find instance of object. Application.OpenForms returns it by name (or number). You had to type cast it to correct type to call method.

(((Main)Application.OpenForms["Main"]).PublicMethodInMain(Args);

OK. Thanks, i shall try it out.

Thanks again

Kez

Thank you so much. It works great. I do however get a warning about a possible System.NullReferenceException. I have enclosed in a try catch block and it seems to work fine. How would i go about removing this warning?

Kez

An alternative way is to pass a handle to the form in its constructor:

public partial class Form2 : Form
    {

        //default constructor
        public Form2()
        {
            InitializeComponent();
        }

        //overloaded constructor with handle to Form1
        public Form2(Form1 frm1Handle)
        {
            //its important to include this in your custom constructors
            //it calls the designer generated code to create the controls on your form
            InitializeComponent();

            HandleToForm1 = frm1Handle;
        }

        //local variable to store handle to Form1
        private Form1 HandleToForm1;

        //when button on form 2 is clicked the test method on instance of Form1 is executed
        private void btnCallToForm1_Click(object sender, EventArgs e)
        {
            HandleToForm1.test();
        }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.