c# - 新表单打开显示文本文件
问题描述
我有两个表单,在我的第一个表单上,我有一个打开 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# 来说相对较新,我将不胜感激。
解决方案
目前尚不清楚您是否只想传递文件名或文件内容。
无论如何,您还需要为您的第二个表单属性 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();
}
推荐阅读
- java - 在quoteMode NON_NUMERIC中编写一个CSV文件,只有字符串和非数字单元格被引号包围
- python - 在为基于 verse 主题的古兰经经文检索系统构建我的 doc2vec 嵌入模型时需要帮助
- python - 库记录器应该只有空处理程序吗?
- swift4.2 - 如何在 Swift 4.2 中使用 SDWebImage 使用 headerView 完成块?
- python - 我用 pyinstaller 创建的 exe 闪烁并终止
- c - C-结构函数
- python-3.x - Opencv中使用multiTracker对象的多对象跟踪初始化
- java - java编译器如何以及在哪里存储.class文件
- java - 如何找到ascii数组的总和?
- c++ - 删除后的c ++指针仍然占用内存