Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I load a CSV file into a DataTable?

Here's a sample that loads a comma separated values (CSV) file into a DataSet.

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;

public class Csv
{
  public static DataSet GetDataSet( string filename )
  {
    string connString =
      string.Format(
        "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Text;",
        Path.GetDirectoryName( filename ) );

    string cmdString =
      string.Format( "SELECT * FROM {0}", Path.GetFileName( filename ) );

    DataSet dataset = new DataSet();
    using ( OleDbConnection conn = new OleDbConnection( connString ) )
    {
      conn.Open();

      OleDbDataAdapter adapter = new OleDbDataAdapter();
      adapter.SelectCommand = new OleDbCommand( cmdString, conn );
      adapter.Fill( dataset, "Test" );

      conn.Close();
    }
    return dataset;
  }
}

Using this DataSet, you can access the DataTable as illustrated in this fragment.

using System.Data;
using System.Windows.Forms;

private void Form1_Load( object sender, System.EventArgs e )
{
  DataSet dataset = Csv.GetDataSet( @"c:\test.csv" );
  dataGrid1.DataSource = dataset.Tables[0].DefaultView;
}

Elan Zhou, Microsoft, and Stuart Celarier, Fern Creek