Showing posts with label Generate DataTable from CSV. Show all posts
Showing posts with label Generate DataTable from CSV. Show all posts

Friday, March 5, 2010

Importing CSV file in a Datagrid in C#

Here is the code for Importing a csv file in the Datagrid.

There are 2 helper methods 'readFile' and 'generateDataTable'

readFile opens the csv and returns its contents.

private string readFile(string filePath)
{

StreamReader streamReader = new StreamReader(filePath);
return streamReader.ReadToEnd();

}

generateDataTableFromCSV generates and returns a DataTable for the provided comma seperated string.

private DataTable generateDataTableFromCSV(string fileContent)
{

DataTable dt = new DataTable();
string[] row = fileContent.Split("\r\n".ToCharArray());

string rowstr = row[0];

string[] col = rowstr.Split(',');
int colCount = 1;
foreach (string colstr in col)
{
dt.Columns.Add(new DataColumn("Column" + colCount));
colCount++;
}

dt.AcceptChanges();
return dt;
}

Here is the code on button click event handler that reads the csv file, and displays it in a datagrid.

private void btnLoad_Click(object sender, EventArgs e)
{
string fileContent = this.readFile(openFileDialog1.FileName);

DataTable dt = this.generateDataTableFromCSV(fileContent);

string[] row = fileContent.Split("\r\n".ToCharArray());
foreach(string rowstr in row)
{
DataRow myRow = dt.NewRow();
int colCount = 0;
string [] col = rowstr.Split(',');

foreach (string colstr in col)
{
myRow[colCount] = colstr;
colCount++;
}

dt.Rows.Add(myRow);
}

gvData.DataSource = dt;

}


For StreamReader we need to use the System.IO;
using System.IO;

here is a screenshot of the form


Feel free to ask me questions and report problems in the C# code.