简体   繁体   English

在中以新形式将文本添加到RichTextBox中

[英]Adding text to RichTextBox in new form in

I have two forms, let's call them Main and Form2 . 我有两种形式,我们称它们为MainForm2
Main form consists of a button and Form2 consists of a RichTextBox . Main窗体由一个按钮组成,而Form2RichTextBox组成。

What I want my program to do is when I click button in the main form it calls function in class DoSomeWork.Do() . 我要我的程序做的是,当我单击主窗体中的按钮时,它将调用DoSomeWork.Do()类中的函数。 Function Do() gets some text from file, it has to open Form2 and paste this text to that RichTextBox . 函数Do()从文件中获取一些文本,它必须打开Form2并将此文本粘贴到该RichTextBox

Problem is that I don't know how to "access" this RichTextBox and paste text to it. 问题是我不知道如何“访问”此RichTextBox并将文本粘贴到其中。

Thanks in advance. 提前致谢。

In Form2 you add a method 在Form2中,您添加一个方法

public void InsertText(string text)
{
    richTextBox1.Text = text;
}

to use the method you open Form2 like this: 使用这样打开Form2的方法:

Form2 f2 = new Form2();
f2.InsertText("hello world");
f2.Show();

You can pass text values through Constructor . 您可以通过Constructor传递文本值。

Eg: create parameterised constructor for Form2 例如:为Form2创建parameterised constructor

Public  Form2(string str)
       {
         this.Value=str;
         InitializeComponent();
        }

NOTE: Value is a public string in form Form2 .and you can set this value to richTextBox in form loading . 注意: ValueForm2形式的公共字符串。您可以在form loading将此值设置为richTextBox。

richTextBox1.Text=Value;

you can create a property on form 2 您可以在表格2上创建一个属性

public string RichTextboxText 
{
    get
    {
        return this.RichTextBox1.Text
    }
    set
    {
        this.RichTextBox1.Text = value;
    }
}

Then create a new form: 然后创建一个新表单:

Form2 f2 = new Form2() { RichtTextBoxText = "I like big butts"; } 
f2.Show();

Something like this should works 这样的事情应该工作

[edit] [编辑]

just like to add that in this way you can also get the value back to from one. 就像以这种方式添加它一样,您还可以将价值从一个值中恢复过来。

in form one at any random point you can do: 在任何随机点以表格1可以执行以下操作:

string RichtEditTextFromForm2 = f2.RichTextBoxText;

given f2 is still active atleast 给定f2至少仍处于活动状态

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

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