Almost all grid components (Wpf/Silverlight), including Wpf C1DataGrid and C1Flexgrid have an 'ItemSource' property that gets or sets the data source of the control. This property accepts objects of type System.Collections.IEnumerable. However, there might be a scenario when user needs to read and load data from a CSV file to the grid. There's no direct property/method available for this and here we discuss how to implement this. We will perform the following steps to implement this :
Here's the function that creates a DataTable, reads the CSV, loads the content to the DataTable and returns the DataTable:
public DataTable GetDataTableFromCSV(string strFileName)
{
try
{
System.Data.OleDb.OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.IO.Path.GetDirectoryName(strFileName) + ";Extended Properties=\\"Text;HDR==YES;FMT=Delimited\\"");
conn.Open();
string strQuery = "Select * from [" + System.IO.Path.GetFileName(strFileName) + "]";
System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
System.Data.DataSet ds = new System.Data.DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{}
return new DataTable();
}
Thereafter we may simply set this DataTable as the grid's ItemSource.
DataTable dt = GetDataTableFromCSV(@"..\\..\\cbp11us.txt");
c1FlexGrid1.ItemsSource = dt.DefaultView;
C1DataGrid.ItemsSource = dt.DefaultView;
And here's how both the grid controls (C1FlexGrid & C1DataGrid) look when populated with data from CSV: Download C# Sample Download Vb.Net sample