Reputation: 1
I am having a problem with updating a textbox inside a form in c#, while loading a second form.
I have two forms in my application. form1
loads first then it loads form2
.
When form2
loads it should update the the textbox.txt
in form1
with some text (in this case: F2:Running
), indicating that it has been loaded.
Any kind of help is appreciated, here's the current code:
namespace EditingBox {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
namespace EditingBox {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
Form2 F2 = new Form2();
Form1 F1 = new Form1();
F2.Show();
textBox1.Select();
textBox1.Refresh();
}
public void textBox1_TextChanged(object sender, EventArgs e) {
}
private void label1_Click(object sender, EventArgs e) {
}
}
}
namespace EditingBox {
public partial class Form2: Form {
public Form2() {
InitializeComponent();
Form1 F1 = new Form1();
F1.textBox1.Select();
F1.textBox1.Text = "F2:Running";
F1.textBox1.Refresh();
}
private void Form2_Load(object sender, EventArgs e) {
Form1 F1 = new Form1();
F1.textBox1.Select();
F1.textBox1.Text = "F2:Running";
F1.textBox1.Refresh();
}
}
}
Upvotes: 0
Views: 44
Reputation: 1746
You need to pass the Form1 this
instance from the original form whenever you create it. Currently:
Form1 F1 = new Form1();
is creating a new instance of form1, not the instance which is displayed. Hence all you need to do is add a Form1 form1 to the constructor of form2 and call that constructor whenever you display it:
public Form2(Form1 F1)
{
InitializeComponent();
F1.textBox1.Select();
F1.textBox1.Text = "F2:Running";
F1.textBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 F2 = new Form2(this);
F2.Show();
textBox1.Select();
textBox1.Refresh();
}
Upvotes: 2
Reputation: 24903
You can pass Form1 to Form2 constructor:
namespace EditingBox
{
public partial class Form2 : Form
{
Form1 _form1;
public Form2(Form1 form1)
{
InitializeComponent();
_form1 = form1;
_form1.textBox1.Select();
_form1.textBox1.Text = "F2:Running";
_form1.textBox1.Refresh();
}
private void Form2_Load(object sender, EventArgs e)
{
_form1.textBox1.Select();
_form1.textBox1.Text = "F2:Running";
_form1.textBox1.Refresh();
}
}
}
Upvotes: 0