简体   繁体   中英

Text file to list box (C#)

This is a project I am having to do as a class assignment.

"Once the file has been selected, the program should read the file (using StreamReader) and load the part number into the first ListBox, one part per line. And the corresponding cost should be loaded into the second ListBox, one per line." The cost is located directly below the part number in the text file.

Such as:

c648

9.60

a813

9.44

c400

0.10

a409

2.95

b920

1.20

This is what I have so far. There is a good chance it is incorrect.

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);
        }

    }   

I need to be able to take all of the part names, such as c948 and place those inside of lstbox1. Then, for lstbox2, the price of 9.60 will be listed. When the file is read, ALL part names and prices should be listed.

So, I need lstBox1 to show c648 (next line) a813. The same for the lstBox2 with cost.

You should loop and read two lines each iteration, one for the part name and another for the cost. Like this:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM