I have a form called “Form1.cs”, which calls a class which we will refer to as “Class1.cs”, as well as another form called “Form2.cs”. A subroutine in Class1 needs to update a textbox in Form2 if that form is open. The text needs to appear after it is appended to the current text in the textbox so that is updates in real time. I can’t figure out how to make this work. I have tried many things and they don’t give me errors but they don’t write the text into the textbox either.
Per request here is my current code. Keep in mind that this is the test project for figuring this out before implementing it into the real one.
Code in Form1.cs
namespace Test
{
public partial class Form1 : Form
{
Form2 cs_form2 = new Form2();
Class1 cs_class1 = new Class1();
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
cs_class1.Writelog();
}
private void Form1_Load(object sender, EventArgs e)
{
cs_form2.Show();
}
public void writeToTextbox()
{
i = 0;
while(i<=10)
{
cs_form2.testTextBox.AppendText("still works");
i++;
}
}
}
}
Code in Form2.cs
namespace Test
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void clear_Click(object sender, EventArgs e)
{
testTextBox.Text = "";
}
public void AppendText()
{
testTextBox.AppendText("asklvhslieh");
}
}
}
Code in Class1
namespace Test
{
class Class1
{
Form2 cs_form2 = new Form2();
public void Writelog()
{
cs_form2.testTextBox.AppendText("asg");
}
}
}
EDIT: By writing
new Form2(), your code inClass1is creating a new instance ofForm2.This instance does not have anything to do with the other instance created in
Form1(also by writingnew Form2()) which is actually visible.You need to give
Class1the existing instance ofForm2, perhaps using a static property (as described below).Pre-Edit
To append text to the textbox, you should call the
AppendTextmethod.To do that outside of
Form2, you should make apublicmethod onForm2that callsAppendText.For example:
To call this method in
Class1, you’ll need a reference to aForm2object.If you only have one
Form2at a time, you can make a static property, like this:In
Class1(or anywhere else), you can then writeNote that you need to do this on the UI thread; if you’re running on a background thread, you can call
BeginInvoke.