首页 > 解决方案 > 新表单打开显示文本文件

问题描述

我有两个表单,在我的第一个表单上,我有一个打开 Txt 文件的按钮,我有第二个表单,上面只有一个文本框,目前我可以在我的第一个表单上打开第二个表单,但是可以t 在表格 2 上显示文本。

目前我正在使用 OpenFileDialog 来选择 txt 文件,但我不确定如何将 txt 文件传递​​到我的第二个表单中。

对于我的第一个名为 form1 的表单,我的按钮上有以下代码,用于打开一个 txt 文件。

 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();
                }

            }
        }

在我的第二个表单中,我只有这个代码,我试图收集并返回 txt 文件(我的文本框位于这个表单上)

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

目前,我能够成功地让我的第二个表单出现在我的第一个表单上,但我的 openFileDialog 中没有显示任何文本(因为我无法弄清楚如何将两者联系在一起。)。

我不太确定如何进行,对于 c# 来说相对较新,我将不胜感激。

标签: c#winforms

解决方案


目前尚不清楚您是否只想传递文件名或文件内容。
无论如何,您还需要为您的第二个表单属性 TextFileName设置一

因此,您可以使用来自第一个表单的文本设置 TextBox

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

现在,当您以第一种形式关闭 OpenFileDialog

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();
}

推荐阅读