C# I try to transfer between 2 form , the value does not pass

I have 2 forms, I open Form2 each time through a different button, button1 OR button2.

Form2: By clicking the button and selecting Checkbox value will set

Form1: will receive the value according to the button pressed.

At this moment Form1 does not receive the value back

Form1

 public partial class Form1 : Form
    {
public string valFrom1;
public string valFrom2;
private void button1_Click(object sender, EventArgs e)
{
     var form1 = new Form2();
     form1.Show();
     valFrom1 = form1.value;
}
private void button2_Click(object sender, EventArgs e)
{
    var form2 = new Form2();
    form2.Show();
    valFrom2 = form2.value;
}

Form2

public partial class Form2 : Form
    {
 public  string value { get; set; }

    public void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                value= "1";
            }
            if (checkBox2.Checked)
            {
                value = "2";
            }
            if (checkBox3.Checked)
            {
                value = "3";
            }
        }

>Solution :

you should use ShowDialog() instead of Show().edit this functiotn:

private void button2_Click(object sender, EventArgs e)
{
   var form2 = new Form2();
   form2.ShowDialog();
   valFrom2 = form2.value;
}

Leave a Reply