Returning data to Forms without opening a new instance

4.8k Views Asked by At

I am trying to return some data from Form2 to Form1, everything seems fine, I got the data and so, but, when I try to pass my data to a textbox, it doesn't changes the text. Only if I open a new instance of Form1, on Form2 it works. Why this happen? Can't I send the text to the old instance?

I'm using this code;

Form1 (Main Form)

public void updateText(string data)
{
    MessageBox.Show(data);
    txtGood.Text = data;
}

Form2 SecondaryForm = new Form2();

SecondaryForm.ShowDialog();

Form2 (Second Form with user data)

Form1 MainForm = new Form1();
MainForm.updateText(data);
MainForm.ShowDialog();
this.Close();

So, my question is, how can I pass the data values to the old instance of the main form? without having to create a new instance and show a new instance. Is there a way to do this?

3

There are 3 best solutions below

1
Haris Hasan On BEST ANSWER

What you can do is pass the reference of MainForm(Form1) to second Form(Form2). Then instead of creating MainForm again use the reference to update the textbox.

   //pass reference to form2
   Form2 SecondaryForm = new Form2(mainForm);
   SecondaryForm.ShowDialog();

    //in the constructor of Form2 save the reference of Form1
    Form1 form1 = null

    Form2(Form1 mainForm)
    {
        form1 = mainForm;
    }

    //then instead of creating a new MainForm again just use reference of Form1

    form1.updateText(data);
    this.Close()
2
Matthew On

This is because you're creating a instance of Form1 in your Form2 code. What you want to do is setup Form2's parentForm to be the instance of the Form1 that created it.

public partial class Form1 : Form
{
    public void CreateForm2()
    {
        Form2 form2 = new Form2(this);
        form2.ShowDialog();
    }

    public string MyTextboxText
    {
        get { return txtMyTextbox.Text; }
        set { txtMyTextbox.Text = value; }
    }
}

public partial class Form2 : Form
{
    private Form1 parentForm;

    public Form2(Form1 parentForm)
    {
        this.parentForm = parentForm;
    }

    public void myButtonClick() 
    {
        parentForm.MyTextboxText = "Hello";
    }
}

This code is just an example, probably wont compile as-is.

0
Dipali Jadhav On

main form:

private void Button2_Click(object sender, EventArgs e) {
    frmCustomersRecord rec = new frmCustomersRecord(this); 
    rec.ShowDialog();
    rec.GetData(); 
}

child form:

public partial class frmCustomersRecord : Form 
{
    public frmCustomersRecord()
    {
        //blank contructor (Instance of an class)
    }

    frmCustomerDetails cd;

    public frmCustomersRecord(frmCustomerDetails parentForm) : this()
    {
        this.cd = parentForm; 
    } 
    //call the methods using child form object
}