【问题标题】:Show text in a richTextBox on a secon form在第二个表单上的 RichTextBox 中显示文本
【发布时间】:2017-02-24 17:43:32
【问题描述】:

在第一个表单上,我有一个加载按钮,用于加载文件并调用第二个表单。在第二种形式中,我有一个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();
            }
        }

    }

如果我尝试将richTextBox 放在第一种形式中的相同代码,它可以工作。

【问题讨论】:

  • ShowDialog() 在那里停止代码,直到对话框关闭,因此您无需向其写入任何内容。使用 Show() 或将文件名作为参数传递给 FormEditor 并以该表单获取它

标签: c# richtextbox


【解决方案1】:

当你打开f2f2.ShowDialog())时,填充richtextbox的代码还没有执行,所以f2上得到一个空的文本框(ShowDialog()后面的代码,一关闭就会执行f2)。试试:

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

【讨论】:

    【解决方案2】:

    FormEditor 应该负责显示文本,而不是当前表单。 为FormEditor编写带参数的构造函数并将文本传递给它,然后将其保存在变量中并在表单加载时将其显示在richtextbox中。

    您的 FormEditor 类应如下所示:

    private string textForEdit{get;set;}
    public FormEditor(string txt)
    {
        textForEdit = txt;
    }
    
    private void FormEditor_load(object sender, EventArgs e)
    {
        richTextBox1.Text = textForEdit;
    }
    

    然后,将 if 块内部更改为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多