Hey,
By default, TextBox are set to private in C#, so in order to access the control on another form, you either have to change the protection level of the form, or create a public property that will set and get the text.
The code that you have above will always return null, since you are creating a new instance of Form2, which will always reset the Text Property of the form. However, I am going to assume that above it not all of the code.
Here is one way of doing it, but bear in mind there are other ways:
Main Form Code:
Code:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SecondForm secondForm = new SecondForm();
secondForm.Owner = this;
secondForm.Show();
}
public string TextBoxText
{
get
{
return this.textBox1.Text;
}
set
{
this.textBox1.Text = value;
}
}
}
Second Form Code:
Code:
public partial class SecondForm : Form
{
public SecondForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MainForm mainForm = (MainForm)this.Owner;
mainForm.TextBoxText = this.textBox1.Text;
}
}
Here I have used the Owner Property to expose a reference to the first form from the second one.
That make sense?
Gary