Sina Razavi
Sina Razavi

Reputation: 45

Change textbox text parent from child form

I have two forms in my program. I have a textbox and a button in both of them. when I click on button in form1, form2 is displayed using showdialog(); When I type in textbox in form2 and click on the button in this form, form2 closes and focus is on form1 and the text that I type in form2 is transferred to a textbox on form1.

How should I do this?

Upvotes: 1

Views: 5544

Answers (4)

Werner van den Heever
Werner van den Heever

Reputation: 753

try this:

(In order) on Form1:

 private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Showdialog();
    this.Hide();
}

then Form2:

 private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2(textBox2.Text);
    frm2.Showdialog();
    this.Hide();
}

then form1:

public partial class Form1 : Form
{
public string textBoxValue;

public Form1()
{
    InitializeComponent();
}

public Form1(string textBoxValue)
{
    InitializeComponent();
    this.textBoxValue = textBoxValue;
}

private void Form1_Load(object sender, EventArgs e)
{
     textBox1.Text = textBoxValue;
}

Upvotes: 0

Jone Polvora
Jone Polvora

Reputation: 2338

In form2, you must change the textbox modifier property to public. This will make the designer generate a public property for the textbox so you can access it anywhere.

When the form2 closes, you simply do:

myTextbox.Text = form2.textBox1.Text;

Upvotes: 0

Amr Hesham
Amr Hesham

Reputation: 339

If you don't care about security, the easiest way would be to declare the TextBox in form1 as public, and then change its text property from form2.

Upvotes: 0

Yaakov Ellis
Yaakov Ellis

Reputation: 41490

  1. Hold a reference in form1 to the instance of form2 that is being shown as a dialog
  2. Expose a public property in form2 giving the contents of the textbox in form2
  3. When form2 closes, the next line of code should access this property and use its value to populate the textbox in form1,

Something like:

Window form2 = new Form2();
form2.ShowDialog();
this.textBox1 = form2.TextBoxValue;

Where form2 has a property defined:

public string TextBoxValue {
  get { return textBox2.Text; }
}

Upvotes: 3

Related Questions