Tom McPherson
Tom McPherson

Reputation: 23

Using a CSV as a datasource for a datagridview in c#

I have a CSV file that I want to be my data source for a datagridview, but before the column headers there are 3 random lines, which are not needed and affect the table

For example:

Username: 01   
Date: 04/02/13   
*blank*            
Source, file, date, time

The code I am using to get the CSV and use it as the datagridview:

{
   string conStr = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + Path.GetDirectoryName(Path.GetFullPath(path)) + ";Extensions=csv,txt";
   OdbcConnection conn = new OdbcConnection(conStr);

   OdbcDataAdapter da = new OdbcDataAdapter("Select * from [" + Path.GetFileName(path) + "]", conn);
   DataTable dt = new DataTable(path);
   da.Fill(dt);

   dataGridView1.DataSource = dt;

   da.Dispose();
   conn.Close();
   conn.Dispose();
}

So basically, I need to read all the CSV for the table, but delete the first 3 lines of the text. Is there a way to do this as a query?

Upvotes: 2

Views: 4562

Answers (2)

Aheho
Aheho

Reputation: 12821

You could use .NET txtReader for Text files

It supports the following connectionstring options that might come in handy for you

  • Skip Rows
  • Has Header
  • Ignore Empty Lines

Here is an example connection string:

 Data Source='C:\MyFolder';Delimiter=',';Has Quotes=True;Skip Rows=0;Has Header=True;
 Comment Prefix='';Column Type=String,String,String,Int32,Boolean,String,String;
 Trim Spaces=False;Ignore Empty Lines=True;

Upvotes: 2

Aheho
Aheho

Reputation: 12821

Insert the following lines after you fill the datatable and before you assign it to your gridview's datasource:

 dt.Rows[0].Delete();
 dt.Rows[1].Delete();
 dt.Rows[2].Delete();
 dt.AcceptChanges();

Upvotes: 0

Related Questions