0

I have two forms, on my first form I have a button to open up a Txt file, I have a second form that only has a textbox on it, currently I am able to open the second form onto my first form, but can't display the text onto form 2.

Currently I am using OpenFileDialog to choose txt file, but I'm unsure as to how to pass the txt file onto my second form.

For my first form called form1 I have the following code on my button meant to open a txt file.

 private void smTxtOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openText = new OpenFileDialog();
            openText.InitialDirectory = @"C:\";
            openText.Filter = "TXT Files(*.txt;)|*.txt;";
            if(openText.ShowDialog() == DialogResult.OK)
            {
                using(StreamReader rdText = new StreamReader(openText.FileName))
                {
                    Form2 newText = new Form2();
                    newText.MdiParent = this;
                    newText.Show();
                }

            }
        }

On my second form I only have this code where I have tried to gather and return the txt file (my textbox is located on this form)

 public TextDocumentForm()
        {
            InitializeComponent();
        }
        public string TextFileName { get { return tbText.Text; } }

At the moment I am able to successfully have my second form appear on my first form, but no text from my openFileDialog is displayed (since I wasn't able to figure out how to tie the two together.).

I'm not really sure how to proceed, being relatively new with c# I would appreciate any help.

Adrian
  • 17
  • 4

1 Answers1

0

It is not clear if you want to pass just the filename or the file content.
In any case, you need to have also a set for your second form property TextFileName

So you can set the TextBox with the text coming from the first form

public string TextFileName 
{ 
   get { return tbText.Text; }  
   set { tbText.Text = value; }
}

Now when you close the OpenFileDialog in your first form

if(openText.ShowDialog() == DialogResult.OK)
{
    // If you want to pass the file content, you read it 
    string fileData = File.ReadAllText(openText.FileName);
    Form2 newText = new Form2();
    newText.MdiParent = this;

    // and pass the content to the set accessor for TextFilename.
    newText.TextFileName = fileData;

    // Of course, if you need to just pass the filename then it is even simpler
    newText.TextFileName = openText.FileName;

    newText.Show();
}
Steve
  • 213,761
  • 22
  • 232
  • 286
  • I apologize as I should've made it clear I was trying to pass the contents of the txt files ( any text written in the file so it can display in my textbox.). Thank you very much for the response, much appreciated! – Adrian Aug 04 '19 at 21:34