Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

c++ cli - How to read next line in csv file on button click

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 ("
"); 
    textBox1->Text += gcnew String (words[11]);
    textBox1->Text += gcnew String ("
");
    textBox1->Text += gcnew String (words[12]);
    textBox1->Text += gcnew String ("
");    
    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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...