简体   繁体   中英

Loading multiple items from a text file to a ListView C#

I am creating a shopping basket form using a windows form application with visual studio, I have a text file with some products in and when the user selects load I want to read the file and then put the data into a ListView but it only does the first item.

Here is my code so far and my results:

private void LoadOrder_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = theDialog.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        System.IO.StreamReader sr = new System.IO.StreamReader(myStream);
                        string fileContent = sr.ReadToEnd();
                        string[] fileItems = fileContent.Split('|');
                        sr.Dispose();

                        ListViewItem lv = new ListViewItem();
                        lv.Text = fileItems[0].ToString();
                        lv.SubItems.Add(fileItems[1].ToString());
                        lv.SubItems.Add(fileItems[2].ToString());
                        basket.Items.Add(lv);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }

Text file:

Banana|6|0.25
Steak|2|1.75
Chips|1|3
Sweets|6|1.5

ListView after Load:

在此处输入图片说明

If anyone can help or point me in the right direction it would be appreciated, thanks!

What you've done here is the following:

  1. You read the entire file and load it into memory
  2. You split the large string into an array
  3. You create and add a ListViewItem using only the first three items of that array.

The last operation is being performed only once, for the first three items. In order to get your desired result you need to perform the last operation in a loop. That way all the data gets parsed. While you're at it, it would be best to read the file in a loop as well, instead of loading it all into memory.

Use this:

if ((myStream = theDialog.OpenFile()) != null)
{
    using (myStream)
    {
        using (var sr = new System.IO.StreamReader(myStream)) // Wrapped it up in a using statement so it is disposed of automagically
        {
            string line = string.Empty;
            while ((line = sr.ReadLine()) != null) // Loop while there is more data to read
            {
                string[] lineItems = line.Split('|'); // Split only the single line

                ListViewItem lv = new ListViewItem();
                lv.Text = lineItems[0];
                lv.SubItems.Add(lineItems[1]);
                lv.SubItems.Add(lineItems[2]);
                basket.Items.Add(lv);
            }
        }
    }
}

What we do here is we read the lines one by one, and then we perform the splitting and creation of the ListViewItem for each line. Keep in mind, this is the most basic code to make it work. Ideally you should add code for validation (ie make sure each line of data is valid for your purposes).

Also, avoid manually disposing of objects like StreamReader . Instead, make use of the using statement, to ensure it is always disposed of properly, even if there is an exception.

In your code you are reading file content and splitting it by | char. That will return you string array that looks like this:

[0]Banana
[1]6
[2]0.25
[3]Steak
[4]2
[5]1.75

etc. Since you have relatively little data, I suggest you to use File.ReadAllLines and then split each line. Something like this:

if (theDialog.ShowDialog() == DialogResult.OK)
{
    var lines = File.ReadAllLines(theDialog.FileName);
    foreach (string line in lines)
    {
        string[] fileItems = line.Split('|');
        ListViewItem lv = new ListViewItem();
        lv.Text = fileItems[0].ToString();
        lv.SubItems.Add(fileItems[1].ToString());
        lv.SubItems.Add(fileItems[2].ToString());
        basket.Items.Add(lv);
    }
}

You need to Loop the fileItems[] array .

where you have

 lv.Text = fileItems[0].ToString();
                    lv.SubItems.Add(fileItems[1].ToString());
                    lv.SubItems.Add(fileItems[2].ToString());
                    basket.Items.Add(lv);

Needs to be wrapped in a Loop

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