2017-02-24 33 views
1

我有一个加载按钮,用于加载文件并调用第二个窗体。在第二种形式我已经有给我从打开的文件文本一个RichTextBox,但它并没有显示什么,这里是我已经尝试过(我做了richTextBox1公众有机会获得它)在第一个窗体上在richTextBox中显示文本

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放入第一种形式,

+0

的ShowDialog()停止代码,直到对话框关闭,所以你不要写任何东西。使用Show()或将文件名作为参数传递给FormEditor并以此形式获取它 – EpicKip

回答

2

当您打开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(); 
} 
相关问题