简体   繁体   中英

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?

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;

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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