Reputation: 1893
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");
}
}
}
Upvotes: 2
Views: 10636
Reputation: 887453
EDIT: By writing new Form2()
, your code in Class1
is creating a new instance of Form2
.
This instance does not have anything to do with the other instance created in Form1
(also by writing new Form2()
) which is actually visible.
You need to give Class1
the existing instance of Form2
, perhaps using a static property (as described below).
To append text to the textbox, you should call the AppendText
method.
To do that outside of Form2
, you should make a public
method on Form2
that calls AppendText
.
For example:
partial class Form2 : Form {
...
public void AppendMyText(string text) {
myTextbox.AppendText(text);
}
...
}
To call this method in Class1
, you'll need a reference to a Form2
object.
If you only have one Form2
at a time, you can make a static property, like this:
partial class Form2 : Form {
static Form2 instance;
public static Form2 Instance { get { return instance; } }
protected override void OnShown(EventArgs e) {
base.OnShown(e);
instance = this;
}
protected override void OnClosed(EventArgs e) {
base.OnClosed(e);
instance = null;
}
In Class1
(or anywhere else), you can then write
if (Form2.Instance != null)
Form2.Instance.AppendMyText(someString);
Note that you need to do this on the UI thread; if you're running on a background thread, you can call BeginInvoke
.
Upvotes: 5