How to read next line in csv file on button click

筅森魡賤 提交于 2019-12-13 09:31:19

问题


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 = ",";
    ...


来源:https://stackoverflow.com/questions/28460546/how-to-read-next-line-in-csv-file-on-button-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!