如何在Windows窗体应用程序中打开txt文件并将行导入文本框

How to open a txt file and import lines to textbox in Windows Forms application

本文关键字:文件 导入 文本 txt Windows 窗体 应用程序      更新时间:2023-10-16

我目前使用的代码本质上是:

private: System::Void toolStripMenuItem3_Click(System::Object^ sender, System::EventArgs^ e) {
OpenFileDialog^ ofd = gcnew OpenFileDialog();
if (ofd->ShowDialog() == System::Windows::Forms::DialogResult::OK) {
//Open file and set to textBox1 - textBox7
}
}

我想做的是打开一个文本文件,然后逐行读取,以指定该行应该进入哪个文本框,数字为1-7。我应该如何在VS Windows窗体应用程序中执行此操作?

这被硬编码为7行,不检查文件末尾读取等。

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
cli::array<TextBox^>^ tbArray = gcnew cli::array<TextBox^>(7)
{
textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7
};
OpenFileDialog^ ofd = gcnew OpenFileDialog();
if (ofd->ShowDialog() == System::Windows::Forms::DialogResult::OK) {
//Open file and set to textBox1 - textBox7
StreamReader^ dataFile = File::OpenText(ofd->FileName);

for (int i = 0; i < 7; i++)
{
tbArray[i]->Text = dataFile->ReadLine()->Trim();
}
dataFile->Close();
dataFile->Dispose();
}
}