Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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.
Posted
Updated 2-May-11 2:13am
v3

Try ReadToEnd method, and don't forget to close your file as soon as you don't need it anymore:
C
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());
    }
}
 
Share this answer
 
Comments
macdonaldgeek 2-May-11 7:47am    
Thanx Olivier, i'll try ReadToEnd and see if it works.
Sergey Alexandrovich Kryukov 2-May-11 8:16am    
Yes, this is the answer, my 5.
--SA
Olivier Levrey 2-May-11 8:19am    
Thank you SA.
Sergey Alexandrovich Kryukov 2-May-11 8:16am    
It does. You better accept the answer formally (green button).
--SA
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.
 
Share this answer
 
Comments
macdonaldgeek 2-May-11 6:33am    
you mean putting + like this or:

this->ReportTextBox->Text=Convert::ToString(line+);
Like this, this->textBox1->AppendText(line);
Olivier Levrey 2-May-11 7:33am    
Good answer, my 5. But you should tell OP about closing the file. Disposing of resources as soon as possible is a part of best practices.
Thanks, I will do that next time:-)
macdonaldgeek 2-May-11 7:49am    
Sure you'll do venkatmakam!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900