0
votes

I want form2 to pass the text in textbox to form1 when it closes.

I have 2 forms as shown in photo. when form2 is opened and when I enter a text then click "send text to form1" nothing happen, the text wont pass to form1 (form2 closes but the textbox in form1 still empty).

I do not know what is wrong. can anyone help me what to do? thank you

photo

Form1:

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Show();

        textBox1.Text = frm2.p;

    }
}

Form2:

public partial class Form2 : Form
{

    string a;

    public string p
    {

        get { return a; }
    }
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        a = textBox1.Text;
        this.Close();
    }
}
2
Because once you show it, it leaves the button click handler and frm2.p hasn't been set yet. Once you set it in button1_Click in form2, you need to tell form 1 to update again. - Ron Beyer
You should really work on improving your variable names. Having variables like a, p frm2, etc. are much harder to understand than meaningful variable names. - Servy

2 Answers

1
votes

The simplest way to solve this is to show form2 as a dialog instead:

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.ShowDialog();  //<-- This line changed.
        //With using ShowDialog(), the code pauses here until frm2 is closed
        //and then resumes on the next line.

        textBox1.Text = frm2.p;

    }
}

The issue is that when you click the button in form 1, it shows form2 and then reads the frm2.p variable right away, without waiting for the user to update it in form2. If you want to keep it as you have it, you need to tell form1 to update itself again.

1
votes

If it's not important for the user to be able to use Form1 while the second form is open (and it's typical in these situations for it to actually be important that they not use it) then simply use ShowDialog rather than Show to show the second form, and then your code will work.

If it's important that the second form not be modal, then you'll need to use an event to update the first form, because as it currently sits you're updating the textbox with the second form's value after showing the form, and the user hasn't entered the value at that time. Here is how you'd use an event to update the first form:

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Show();

    fm2.FormClosed += (s, args) => textBox1.Text = frm2.p;
}