简体   繁体   English

如何将文本从C#Winform中的另一个类追加到richTextBox?

[英]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 . 我创建了一个名为Form1 richTextBox1和一个名为richTextBox1的RichTextBox。 Also I have created a method called update which does the work of displaying message in the richTextBox1. 我还创建了一个名为update的方法,该方法可以在richTextBox1中显示消息。 When I tried to invoke it from Class1 it is not working. 当我尝试从Class1调用它时,它不起作用。 Whereas I am to see the message in the MessageBox whereas not in the richTextBox1 . 而我要在MessageBox中看到消息,而不是在richTextBox1 Here is the piece of code. 这是一段代码。

Code: Form1.cs 程式码: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 将Class1.cs

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

try this: 尝试这个:

Class1.cs 将Class1.cs

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

Form1.cs 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();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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