文本文件到列表框(C#)
本文关键字:列表 文件 文本 | 更新日期: 2023-09-27 18:20:04
这是一个我必须作为类赋值来完成的项目。
"选择文件后,程序应读取文件(使用StreamReader),并将零件号加载到第一个ListBox中,每行一个零件。相应的成本应加载到第二个ListBox,每行1个。"成本位于文本文件中零件号的正下方。
例如:
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也是如此。
每次迭代都应该循环读取两行,一行用于零件名称,另一行用于成本。像这样:
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
}
}