0

I have been digging from last 4 hours to find a simplest solution to import a csv file into datagridview in C# and i am unable to find the appropriate solution.

then hopelessly, I decided to ask user to convert csv to excel first and then import but its too unromantic. here is the code for importing excel:

        string pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtPath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
        OleDbConnection conn = new OleDbConnection(pathConn);
        OleDbDataAdapter ODA = new OleDbDataAdapter("Select *from [" + txtSheet.Text + "$]", conn);
        DataTable dt = new DataTable();
        ODA.Fill(dt);
        dataGridView1.DataSource = dt;

Question: To import CSV, what should be the connectionString using this code.? Or there is no simple soultion?

Usama Khan
  • 1
  • 1
  • 4
  • 1
    see this post [here](http://stackoverflow.com/questions/14157153/faster-way-of-reading-csv-to-grid) in stackoverflow – fabricio Feb 24 '16 at 16:43
  • 1
    Side note: beware of sql injection - you should never build your query by *concatenating text values from users*. Instead use parameterized queries as seen in these examples [here](http://stackoverflow.com/q/12048152/3773066) and [here](http://stackoverflow.com/q/9401888/3773066). – OhBeWise Feb 24 '16 at 16:54
  • the connection string is different for text files http://stackoverflow.com/questions/6813607/parsing-csv-using-oledb-using-c-sharp, https://www.connectionstrings.com/textfile/ – Slai Sep 05 '16 at 23:18

1 Answers1

1

I have this snippet from my old project, hope this helps:

string csvFile = System.IO.Path.Combine(Application.StartupPath, "aCSVfile.csv");
List<string[]> rows = File.ReadAllLines(csvFile).Select(x => x.Split(',')).ToList();
DataTable dataTable = new DataTable();

//add cols to datatable:
dataTable.Columns.Add("col0");
dataTable.Columns.Add("col1");

rows.ForEach(x => { dataTable.Rows.Add(x); });

dataGridView.DataSource = dataTable;
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
jomsk1e
  • 3,585
  • 7
  • 34
  • 59