简体   繁体   中英

How to append text to the richTextBox from another class in C# Winform?

I have created a Winform named Form1 with a RichTextBox named richTextBox1 . Also I have created a method called update which does the work of displaying message in the richTextBox1. When I tried to invoke it from Class1 it is not working. Whereas I am to see the message in the MessageBox whereas not in the richTextBox1 . Here is the piece of code.

Code: Form1.cs

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void update(string message)
        {
            richTextBox1.AppendText("mess: " + message);
            MessageBox.Show(message);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 sample = new Class1();            
        } 
    }

Class1.cs

public class Class1
    {        
        public Class1()
        {
            Form1 form = new Form1();
            form.update("Sampe");
        }        
    }

try this:

Class1.cs

 class Class1
    {
        public Class1()
        {
            Form1._Form1.update("Sampe");
        } 
    }

Form1.cs

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            _Form1 = this;
        }
        public static  Form1 _Form1;
        public void update(string message)
        {
            richTextBox1.AppendText("mess: " + message);
            MessageBox.Show(message);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 sample = new Class1();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM