How to read next line in csv file on button click

2019-09-21 01:16发布

问题:

I have a windows form with two butttons and a text box. My start button reads the first line in the csv file and outputs the data I want into a textbox:

private: System::Void StartBtn_Click(System::Object^  sender, System::EventArgs^  e)
{ 
    String^ fileName = "same_para_diff_uprn1.csv";
    StreamReader^ din = File::OpenText(fileName);

    String^ delimStr = ",";
    array<Char>^ delimiter = delimStr->ToCharArray( );   
    array<String^>^ words;
    String^ str = din->ReadLine();

    words = str->Split( delimiter ); 

    textBox1->Text += gcnew String (words[10]);
    textBox1->Text += gcnew String ("\r\n"); 
    textBox1->Text += gcnew String (words[11]);
    textBox1->Text += gcnew String ("\r\n");
    textBox1->Text += gcnew String (words[12]);
    textBox1->Text += gcnew String ("\r\n");    
    textBox1->Text += gcnew String (words[13]);

Then my 'next button' I want it to clear the text box, and display the next lines data as above. Then everytime the next button is cliced, the textbox is cleared and the next line of the csv file is shown. Until I get to the end of the file. How would I manage that?

TIA

回答1:

Your problem is that your button_click() function forgets the StreamReader object and all other variables after it has finished.
You need to make some of the variables (at least din) independent from the function, defining them as members of your WinForms object. Whenever you call the function, you can read the next line then. And you need to add a check whether din is nullptr (will be so at the first call), then load the file, otherwise just use it:

StreamReader^ din;

private: System::Void StartBtn_Click(System::Object^  sender, System::EventArgs^  e)
{ 
    String^ fileName = "same_para_diff_uprn1.csv";
    if (!din)  // or: if (din == nullptr)
        din = File::OpenText(fileName);

    String^ delimStr = ",";
    ...


标签: c++-cli