如何将文件内容显示到文本框中? [英] How to display contents of a file to a text box?
问题描述
单击按钮控件后,我想将文件(data.txt)的内容显示到文本框或标签控件中.但是下面的代码只给我一行,而我希望从文件中检索全部内容.
这是我到目前为止的内容:
I want to display the contents of a file (data.txt) to a text box or label control once I click button control. But the code below only gives me one line, while I want the whole content to be retrieved from the file.
This is what I have so far:
private: System::Void Report_Click(System::Object^ sender, System::EventArgs^ e) {
try
{
FileStream^ fs = gcnew FileStream(L"data.txt", FileMode::Open);
StreamReader^ sr = gcnew StreamReader(fs);
int count = 0;
for(;;)
{
String^ line = sr->ReadLine();
count++;
if (line == nullptr) break;
this->ReportTextBox->Text=Convert::ToString(line);
}
}
catch(System::Exception^ pe)
{
Console::WriteLine(pe->ToString());
}
}
提前感谢您可以提供的任何帮助.
Thanx in advance for any kind of help you can give me.
推荐答案
尝试ReadToEnd
方法,不要忘记尽快关闭文件不再需要它了:
TryReadToEnd
method, and don''t forget to close your file as soon as you don''t need it anymore:
System::Void Report_Click(System::Object^ sender, System::EventArgs^ e)
{
try
{
StreamReader^ sr = gcnew StreamReader(L"data.txt");
//read the whole file
this->ReportTextBox->Text = sr->ReadToEnd();
//don't forget to close your file
sr->Dispose();
}
catch(System::Exception^ pe)
{
Console::WriteLine(pe->ToString());
}
}
我不知道托管c ++ \ CLI.我正在VC ++中工作.但是从代码中来看,
I do not know about Managed c++\CLI.I am working in VC++.But from the code,
this->ReportTextBox->Text=Convert::ToString(line);
我知道您在每个循环中用新行替换文本框的当前文本.因此最终您在文本框(最后一行)中将只有一行.如果我确定会有+运算符来附加文本.
I understood that you are replcing the current text of textbox with new line in each loop.So you at the end you will have only one line in textbox(last line).If i am sure there will be + operator to append the text.
这篇关于如何将文件内容显示到文本框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!