2015-11-02 73 views
-1

这是一个我不得不作为课堂作业的项目。文本文件到列表框(C#)

“一旦文件被选中,程序应该读取文件(使用StreamReader)并将零件编号加载到第一个ListBox中,每行一个零件,相应的成本应该加载到第二个ListBox,一个每行“。成本位于文本文件中的零件编号的正下方。

如:

c648

9.60

A813

9.44

C400

0.10

A409

2.95

B920

1.20

这是我到目前为止所。这很可能是不正确的。

private void readToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      StreamReader srdInput;    
      dlgOpen.Filter = "Text Files (*.txt) |*.txt|All Files (*.*)|*.*"; 
      dlgOpen.InitialDirectory = Application.StartupPath; 
      dlgOpen.Title = "Please select the PartsCost file."; 

      if (dlgOpen.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       srdInput = File.OpenText(dlgOpen.FileName); 
      } 
     } 

     catch (Exception ex) 
     { 
      MessageBox.Show("Error while trying to read input file." + "/n" + ex.Message); 
     } 

    } 

我需要能够采取所有的部分名称,如c948和放置在lstbox1里面。然后,对于lstbox2,将列出9.60的价格。读取文件时,应列出所有零件名称和价格。

所以,我需要lstBox1显示c648(下一行)a813。成本相同的lstBox2。

回答

0

您应循环读取两行,每次迭代一次,一次用于零件名称,另一次用于成本。像这样:

using (StreamReader srdInput = File.OpenText(dlgOpen.FileName)) 
{ 
    while (!srdInput.EndOfStream) 
    { 
     string line1 = srdInput.ReadLine(); 
     string line2 = srdInput.ReadLine(); 

     //Insert line1 into the first ListBox and line2 into the second listBox 
    } 
}