Monday, June 29, 2015

CSV to DataGridView

Sample code to show the content of the CSV (Comma Separated File) in DataGrid View with the filter & sorting in C#.

Namespace :

using System.Data.OleDb;


Code:

 OleDbConnection conn = new OleDbConnection
           ("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
             Path.GetDirectoryName(@"D:\TEST\test.txt") + 
             "; Extended Properties = 'Text;FMT=Delimited'");

            conn.Open();

            OleDbDataAdapter adapter = new OleDbDataAdapter
                   ("SELECT * FROM " + Path.GetFileName(@"D:\TEST\test.txt"), conn);

            DataSet ds = new DataSet("Temp");
            adapter.Fill(ds);

            conn.Close();

            dataGridView1.DataSource = ds.Tables[0] ;    


You can add the filter condition on dataset as below,
First create the Default view from the DatagridView datasource.

  string rowFilter = string.Format("column1 LIKE '%{0}%' AND column2 = 1",
                                  "test");
            (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = rowFilter;

         

If you want to sort the DatagridView, set the sort column to the Default view.
.

   (dataGridView1.DataSource as DataTable).DefaultView.Sort = "column1";

No comments:

Post a Comment