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

我当前正在使用的代码本质上是:

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窗体应用程序中执行此操作?

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

这被硬编码为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();

        }
    }
本文链接:https://www.f2er.com/3084140.html

大家都在问