Reputation: 69
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)
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.
Upvotes: 1
Views: 95
Reputation: 880
FormEditor should be reponsible of showing the text, not the current form. 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.
Your FormEditor class should look like this:
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:
using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
{
FormEditor f2 = new FormEditor(sr.ReadToEnd());
f2.ShowDialog();
}
Upvotes: 2
Reputation: 14389
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
). Try:
FormEditor f2 = new FormEditor();
using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
{
f2.richTextBox1.Text = sr.ReadToEnd();
}
f2.ShowDialog();
Upvotes: 2