2

I'm trying to import CSV and display the data in DataGridView by using the way that i can understand.
Here is the code and the explanation that i understand how it works so far.
Please do correct me if i miss understand.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test2
{
    public partial class Form1 : Form
    {   
        //Open the choose GUI to choose the file that we want to import
        OpenFileDialog openFile = new OpenFileDialog();

        public Form1()
        {
            InitializeComponent();
        }


        private void Button1_Click(object sender, EventArgs e)
        {   
            //if open successfully, then apply streamReader to it
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(openFile.FileName);
                //read the data in the file by using readLine
                var rl = sr.ReadLine();

                // If the rl is not null, then print (is it correct?)....
                if(rl != null)
                {
                    ///code to print data
                }
            }
        }

        //filter out the csv file.
        private void Form1_Load_1(object sender, EventArgs e)
        {
            openFile.Filter = "CSV|*.csv";
        }

    }
}

Now, i'm trying to print the data.
I know i need to use DataGridView.DataSource to print the data(correct me if i'm wrong) but i have no idea how to apply.
So, is my explain is true or is there anything i have add???
--beginner.

Sample data image. enter image description here

ccs
  • 151
  • 2
  • 15
  • One way is to create DataTable and columns should match the content with your CSV file and assign Datatable to Grid. – faheem khan Jun 13 '17 at 08:28

1 Answers1

2

You can build a List (of string, or whichever data type you want) and use it as DataSource. Assuming the x:name of your DataGridView is dgv.

private void Button1_Click(object sender, EventArgs e)
{
    //if open successfully, then apply streamReader to it
    if (openFile.ShowDialog() == DialogResult.OK)
    {
        List<string[]> rows = System.IO.File.ReadAllLines(openFile.FileName).Select(x => x.Split(',')).ToList();
        System.Data.DataTable dt = new System.Data.DataTable();
        List<string> headerNames = rows[0].ToList();
        foreach (var header in headerNames)
        {
            dt.Columns.Add(headers);
        }
        foreach (var x in rows.Skip(1))
        {
            if (x.SequenceEqual(headerNames))   //linq to check if 2 lists are have the same elements (perfect for strings)
                continue;     //skip the row with repeated headers
            dt.Rows.Add(x);
        }
        dgv.DataSource = dt;
    }
}

Remember to add using System.Linq;.

Do ask if any part is unclear. You can add more checking to the 2nd foreach loop (e.g. check if all the items in the row are empty).

My answer is based on: Faster way of reading csv to grid

For best way of checking 2 lists equality: Check if two lists are equal

Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41
  • it print out | lenght | , i think there is something wrong | 340 | – ccs Jun 13 '17 at 08:41
  • Try the edited code, I didn't realize it was reading just the first line. This should get all lines. However, since I don't know the format of your csv, this code assumes there is only 1 column. If you provide the number of columns, or column names, I can refine my answer better for you. – Keyur PATEL Jun 13 '17 at 08:51
  • Let's assume that if there are different csv file with diffrent number of column and row, How should i do??? I would like to make it "Flexible" to every Csv File. – ccs Jun 13 '17 at 08:55
  • I have to idea why it output the data, refer to the question i just update. – ccs Jun 13 '17 at 08:59
  • Ah I understand, you want to keep header names as first line and dynamically populate the DataGridView. Let me modify my answer to suit that. – Keyur PATEL Jun 13 '17 at 09:01
  • your answer did help to output !! But do u have any idea how can i filter all the repeated header so it do not shows the repeated header in the output? As u can see from the data sample image, it have repeated header. What i want to do is only the header do not repeat and show is the column. – ccs Jun 13 '17 at 09:18
  • You can add checking in the second foreach loop, let me update my answer to try to help. – Keyur PATEL Jun 13 '17 at 09:21
  • thank you for your help! It's works! I have post a new question at https://stackoverflow.com/questions/44534219/remove-unnecessary-white-space-auto-detect-header-and-sorted-by-name-in-datagr to avoid extended discussion in comments. – ccs Jun 14 '17 at 02:12