简体   繁体   English

将多个项目从文本文件加载到ListView C#

[英]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. 我正在使用带有Visual Studio的Windows窗体应用程序创建购物篮窗体,我有一个包含某些产品的文本文件,当用户选择加载时,我想读取该文件,然后将数据放入ListView中,但它只第一项。

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: 加载后的ListView:

在此处输入图片说明

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. 您仅使用该数组的前三个项目创建并添加ListViewItem

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. 我们在这里所做的是先逐行阅读各行,然后为每行执行ListViewItem的拆分和创建。 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 . 另外,请避免手动处置StreamReader之类的对象。 Instead, make use of the using statement, to ensure it is always disposed of properly, even if there is an exception. 相反,请使用using语句,以确保始终将其正确处理,即使有异常也是如此。

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. 等等。由于您的数据相对较少,建议您使用File.ReadAllLines ,然后拆分每一行。 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 . 您需要循环fileItems []数组。

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 需要包裹在一个循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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