1

I have two differents forms form1 and form2. When I insert text into textbox on form2 and confirm it whit button, then form1 creates new (opens up) form1 whit updated data, instead of updating exsisting form.

private void button1_Click(object sender, EventArgs e)
    {
              //This is my problem
                text = textBox1.Text;
                new Form1().Show();
                this.Close();
    }
        

Is there any way to change new to update? And I'm new to forms. There is photo example of what I try to do. Example1

And I want to update same form, after entering data in second form.

Example2

Community
  • 1
  • 1
Slasher
  • 568
  • 7
  • 29
  • 1
    There is a lot of possibilities to do this. Simplest one is to pass the reference to the main form to the secondary form and change the text in the click handler. – Hamlet Hakobyan Dec 27 '16 at 18:24
  • Could you show me your solution on code example? Its hard to follow from text. – Slasher Dec 27 '16 at 18:32

2 Answers2

1

In your 2nd form create a property that you can set before you open the 2nd form. Make that property so it is a reference type. After the 2nd form closes your reference type will have that value. Like this:

2nd Form:

SomeObject FormOneNeedsThis { get; set; }

1st Form:

SomeObject a = new SomeObject();
secondForm.FormOneNeedsThis = a;

After 2nd form is closed, 1st form can do this:

this.someLabel.Text = a.SomeProperty;
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
1

You are explicitly creating a new instance of the class Form1 and calling the method "Show()" on the 5th line.

To better accomplish what you want, I would use something like this instead:

In Form2:

1) Assign the DialogResult property to the buttons as "OK" or "Cancel" according to the case. You shouldn't need to define the OnClick Event on the buttons on Form2

2) Set the Modifiers property of the text box as "public"

In Form1:

In the method that is opening the dialog:

private void OpenDialog() 
{
   Form2 f = new Form2();
   //show the form as a Dialog and returns the DialogResult
   if (f.ShowDialog() == DialogResult.OK) //only if the user pressed OK
   {
        //assign the value of the textbox in form2 to label1
        label1.Text = f.textBox1.Text;
   }     
}
dns_b
  • 81
  • 6