-3

So this is a bit different to what I've seen:

How to change text in a textbox on another form in Visual C#?

I have a form (Form1) that runs when my C# application runs. A button Form1 opens Form2. On Form2, I have another button to set the text of the textbox on Form1, to the same value as a textbox on Form2.

Using a similar approach to:

Form1 frm1 = new Form1(); frm1.TextBoxValue = "SomeValue";

Doesn't work as it opens a new form completely, but I want to change the form1 that is already open, can someone please assist?

A bit new
  • 91
  • 1
  • 9
  • If you want to work with an existing form, you dont use `new` to create a new instance. use the one that is already open – Ňɏssa Pøngjǣrdenlarp Sep 01 '18 at 15:45
  • All the open forms (including the main one) are kept by the framework in the Application.OpenForms collection. You just need to search that collection for a form with the Type matching the desidered one. – Steve Sep 01 '18 at 15:48
  • 1
    This question gets asked 100x every day and gets answered and any of those answers should work for you. – TaW Sep 01 '18 at 15:53

3 Answers3

2

You must store Textboxvalue on Form2 in some property like this:

public string ReturnValue {get;set;} 

private void Form2_button2_Click(object sender, EventArgs e)
{
     ReturnValue = txtInput.Text;
}

Or You can change the access modifier for the generated field in Form2.Designer.cs from private to public.

Change this

private System.Windows.Forms.TextBox txtInput;

by this

public System.Windows.Forms.TextBox txtInput;

Then in Form1 you can get Value of ReturnValue When end user close Form2

private void Form1_popupButton_Click(object sender, EventArgs e)
    {
       Form2 frm = new  Form2();
       frm.ShowDialog();

      // get ReturnValue from form2
      string ReturnValue = frm.ReturnValue ;
      //get txtInput value directly
      ReturnValue = frm.txtInput.Text;
}
Hossein
  • 3,083
  • 3
  • 16
  • 33
0

I would like to help you as good as I can but the information you provided is not that clear to me.

What you could do is when creating a new form use the constructor to pass the text

E.G.

Form1 frm1 = new Form1("some value or variable");

When you need tailored information please provide more code and a better explanation of your problem.

o elhajoui
  • 394
  • 4
  • 14
0

You could create a constructor for Form2 that takes in Form1 as a parent:

public partial class Form2 : Form
{
    Form1 Parent { get; }
    public Form2(Form1 parent)
    {
        Parent = parent;
        Parent.TextBoxValue = "SomeValue";
    }
}

However I don't think this is good practice. If your Form2 needs to be passing a result back to Form1, then you need to reverse your approach. Instead you should have a public property or method on Form2 that you can assign from inside Form1.

Parrish Husband
  • 3,148
  • 18
  • 40