The OrangeGoblin
The OrangeGoblin

Reputation: 794

Append text to RichTexBox from anywhere in my application

I am trying to 'Append' text to a Richtextbox I am using as a log window to show events from my Winforms application, from other service classes. To be clear, I want to append the text.

I have tried all of what has been suggested on here. I have set a public property in the form, I have created a delegate, I have created a class to handle it. But it won't append the text, it either clears the window (when I use var f = new Form1();, I do understand why this happens as it is creating a new Form in memory)

The closest I am to making it work is the following class I have written.

class RichTextBoxAppend
    {        
        public static void AddNewText(string message, Form1 f)
        {
            f.richLogWindow.AppendText(DateTime.Now.ToString() + ": " + message + "\r\n");
        }
    }

I call it from another class method by the following:

public SomeClass{
    public SomeMethod(){
        //Some stuff happens here
        RichTextBoxAppend.AddNewText("Some message", Form1);
    }
}

The error I am getting is

'Form1' is a type, which is not valid in the given context

I don't want to create a new Form in memory as this clears out the Richtextbox.

In summary, I want to "Append" text from anywhere in my application, without clearing out the Richtextbox.

TIA

Upvotes: 0

Views: 184

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18155

You need to pass the instance of Form1 right from the way it is created to where is being consumed. For example,

Believe you are invoking SomeClass.SomeMethod from your Form1 (in case, you have some other intermediate class, keep passing Form Instance as described here).

First, you need to rewrite your SomeClass and RichTextAppend Class as follows.

class RichTextBoxAppend
{
    public static void AddNewText(string message, Form1 f)
    {
         f.RichText.AppendText(DateTime.Now.ToString() + ": " + message + "\r\n");
     }
}

public class SomeClass
{
    public void SomeMethod(Form1 form)
    {
        //Some stuff happens here
        RichTextBoxAppend.AddNewText("Some message", form);
    }
}

And then, from the location from which you invoke the SomeClass.SomeMethod, (in this case,assume it happens in an Button Click event), you need to pass Form Instance to your SomeMethod.

public partial class Form1 : Form
{
public RichTextBox RichText => richLogWindow;
private void button1_Click_1(object sender, EventArgs e)
{
   var someclass = new SomeClass();
   someclass.SomeMethod(this);
}
}

In the following line, you are passing the instance of Form1 to SomeMethod (since you are refering "this" within Form1, it refers to instance of Form1)

someclass.SomeMethod(this);

By passing the form instance right from the your form to classes which require it, you can access the instance.

Upvotes: 1

Related Questions