NerdJam NerdJam - 2 months ago 15
C# Question

Making instances of forms public C#

I am attempting to pass information from a child form to a parent. I have been using the following code I found on a forum to help me:

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

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

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

public void msgme()
{
MessageBox.Show("Parent Function Called");
}

}
}


Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace childform
{
public partial class Form2 : Form
{
private Form1 m_parent;

public Form2(Form1 frm1)
{
InitializeComponent();
m_parent = frm1;
}

private void button1_Click(object sender, EventArgs e)
{
m_parent.msgme();
}
}
}


Which works and is all well and good. Trouble is, my program requires me to set variables within tempDialog, from Form 1, in methods other than button1_Click. But, these cannot find the instance of tempDialog because it is in button1_click.

Also, I cannot move it out of a method (say, into the class) because then the 'this' modifier does not reference Form1...

Any ideas how I can reference Form1 from Form2 AND vice versa? Using this code or otherwise?

Thanks

Answer

I'm not sure what you mean by your last comment about this. Make a field that references Form2 and initialize it in the constructor. Then you can reference _form2 in other methods of Form1.

public partial class Form1 : Form
{
    private Form2 _form2;
    public Form1()
    {
        InitializeComponent();
        _form2 = new Form2(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _form2.ShowDialog();
    }

}

This sort of thing can get difficult to follow, when complexity increases. A better way might be to make Form1 and Form2 have references to some common object that they can both manipulate.