简体   繁体   English

在secon表单上的richTextBox中显示文本

[英]Show text in a richTextBox on a secon form

on the first form I've a load button that load the file and call the second form. 在第一种形式上,我有一个加载按钮,用于加载文件并调用第二种形式。 In the second form I've a richTextBox that has to show me text from the opened file, but it doesn't show nothing, here is what i've tried (I made richTextBox1 public to have access to it) 在第二种形式中,我有一个richTextBox,它必须向我显示打开的文件中的文本,但不显示任何内容,这是我尝试过的内容(我公开了richTextBox1以对其进行访问)

private void btnLoad_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();

        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            FormEditor f2 = new FormEditor();
            f2.ShowDialog();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
            {
                f2.richTextBox1.Text = sr.ReadToEnd();
            }
        }

    }

If I try the same code putting richTextBox in the first form it works. 如果我尝试用相同的代码将richTextBox放在第一种形式中,它将起作用。

When you open f2 ( f2.ShowDialog() ), the code for filling richtextbox has not been executed, so you get an empty textbox on f2 (The code after ShowDialog() , will execute as soon as you close f2 ). 当您打开f2f2.ShowDialog() )时,尚未执行填充f2.ShowDialog()的代码,因此您在f2上获得了一个空文本框( ShowDialog()之后的代码将在您关闭f2立即执行)。 Try: 尝试:

FormEditor f2 = new FormEditor();
using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
{
     f2.richTextBox1.Text = sr.ReadToEnd();
}
f2.ShowDialog();

FormEditor should be reponsible of showing the text, not the current form. FormEditor应该负责显示文本,而不是当前表单。 Write constructor with parameter for FormEditor and pass text to it, then save it in a variable and show it in richtextbox on form load. 使用FormEditor的参数编写构造函数,并将文本传递给它,然后将其保存在变量中,并在加载表单时在richtextbox中显示。

Your FormEditor class should look like this: 您的FormEditor类应如下所示:

private string textForEdit{get;set;}
public FormEditor(string txt)
{
    textForEdit = txt;
}

private void FormEditor_load(object sender, EventArgs e)
{
    richTextBox1.Text = textForEdit;
}

Then, change inside of your if block to this: 然后,在您的if块内部更改为:

using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
{
    FormEditor f2 = new FormEditor(sr.ReadToEnd());
    f2.ShowDialog();
}

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

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