The way you current code is structured, you are creating a new
form each time you call AddLog
. This is not the existing form that is visible, but rather a new one that isn't shown. You are adding the contents of variable s
to the TextBox
on this new form. The form is never shown, and since it's a local variable, it is eligible for garbage collection after this method is done running.
The Log
class needs to have a reference to the existing form that is shown so it can add it to the correct instance. You could do something like:
public class Log
{
private Form1 _form;
public Log(Form1 formToUpdate)
{
_form = formToUpdate;
}
public void AddLog(string s)
{
_form.richTextBox1.Text += Environment.NewLine + s;
}
}
But now you Log class is tied to a very specific form and it is directly messing around with a specific UI control on that form is doesn't own. This is very bad design.
Better ways to do this would to be for the Log class to raise an event which Form1
would subscribe to (assuming it makes sense for the form to have a reference to a Log
instance). You could also create an interface for Form1
to implement and then have the constructor for Log
take that interface type rather than a specific concrete type.
You need to learn about the basics of references, instance, constructors, etc.