Results 1 to 2 of 2

Thread: Help Importing CSV into Listview

  1. #1

    Thread Starter
    Member
    Join Date
    Feb 2021
    Posts
    41

    Help Importing CSV into Listview

    I need a way to open a csv file and write the contents of it into a listview component.
    I tried but it doesn't work.

    Here is my code:

    Code:
            private async void savCoord_Click(object sender, EventArgs e)
            {
    
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.InitialDirectory = Path.GetPathRoot(Environment.SystemDirectory);
                saveFileDialog.Filter = "CSV|*.csv";
    
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    using (var writer = new StreamWriter(saveFileDialog.FileName))
                    {
                        foreach (ListViewItem item in PositionsListView.Items)
                        {
                            await writer.WriteLineAsync($"{item.Text},{item.SubItems[1].Text},{item.SubItems[2].Text},{item.SubItems[3].Text}");
                        }
                        MessageBox.Show("Success!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
    
                }
            }
    
    
            private void openCoord_Click(object sender, EventArgs e)
            {
    
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = Path.GetPathRoot(Environment.SystemDirectory);
                openFileDialog.Filter = "CSV|*.csv";
    
                try
                {
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string sFileName = openFileDialog.FileName;
                        foreach (var line in File.ReadLines(sFileName))
                        {
                            var fields = line.Split(',');
                        }
                        
                        }
                }
                catch (Exception errorMsg)
                {
                    MessageBox.Show(errorMsg.Message, "Error reading a file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
    
            }
    It won't write display the data! please help!

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Help Importing CSV into Listview

    I trued to reply at the other site but it's playing up right now, so I'll copy my reply here:

    Think about the steps:

    1. Get the field values from the current line of the file.
    2. Create a ListViewItem containing the field values from 1.
    3. Add the ListViewItem from 2 to the ListView.


    You've already got 1 from my code:
    Code:
    var fields = line.Split(',');
    You're creating a ListViewItem here:
    Code:
    ListViewItem item = new ListViewItem(line.ToString());
    but you're not using those field values to populate it. The documentation I directed you to contains this:
    Code:
    ListViewItem item1 = new ListViewItem("item1",0);
    // Place a check mark next to the item.
    item1.Checked = true;
    item1.SubItems.Add("1");
    item1.SubItems.Add("2");
    item1.SubItems.Add("3");
    so that shows you how to create a ListViewItem, set the Text or the item itself and then add three more subitems. Does that sound a little like what you want to do? You just have to substitute the text values that you already have for the values they use in the example. If you made the effort to use the documentation then you would know that the constructor they are using takes an index for the image but there's another constructor that takes just the text for those not using images. You're also not using check boxes:
    Code:
    var item = new ListViewItem(fields[0]);
    
    item.SubItems.Add(fields[1]);
    item.SubItems.Add(fields[2]);
    item.SubItems.Add(fields[3]);
    If you made just a little more effort then you'd know that there's another constructor that takes a string array, which fields is:
    Code:
    var item = new ListViewItem(fields);
    Now all that remains is to add the ListViewItem you just created to the ListView:
    Code:
    PositionsListView.Items.Add(item);
    That's following some simple logic and using the information that you already have at your fingertips. Follow instructions when they're provided. Read the relevant documentation. Think about the logic required first and write code to implement that logic specifically. It takes some practice but you need to make sure that you're practicing the right things. This process will become second nature in time.

    Now, while that will achieve your aim, it does have an issue. Adding items to a ListView one by one like that is slow, because the control redraws after each item. That's not too big a deal if the number of items is small but performance can be horrendous for large numbers of items. There are two ways to address this issue; one is good and the other better.

    The good way is to call BeginUpdate on the control before you start adding items and EndUpdate after you finish. That will prevent the control redrawing between adding items. The better way is to add all the items to a List<ListViewItem> first, then add them all to the ListView in a batch with a call to AddRange:
    Code:
    var items = new List<ListViewItem>();
    
    foreach (var line in File.ReadLines(filePath))
    {
        items.Add(new ListViewItem(line.Split(',')));
    }
    
    PositionsListView.Items.AddRange(items.ToArray());
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width