I want to import data from a text file and to display it in a data grid. The text file is delimited.The first row contains column headers and the rest contains the data for
why you want to create the class?? you can use the below code as well.. it will dynamically make the DataTable
check here as well..
public class Helper
{
public static DataTable DataTableFromTextFile(string location, char delimiter = ',')
{
DataTable result;
string[] LineArray = File.ReadAllLines(location);
result = FormDataTable(LineArray, delimiter);
return result;
}
private static DataTable FormDataTable(string[] LineArray, char delimiter)
{
DataTable dt = new DataTable();
AddColumnToTable(LineArray, delimiter, ref dt);
AddRowToTable(LineArray, delimiter, ref dt);
return dt;
}
private static void AddRowToTable(string[] valueCollection, char delimiter, ref DataTable dt)
{
for (int i = 1; i < valueCollection.Length; i++)
{
string[] values = valueCollection[i].Split(delimiter);
DataRow dr = dt.NewRow();
for (int j = 0; j < values.Length; j++)
{
dr[j] = values[j];
}
dt.Rows.Add(dr);
}
}
private static void AddColumnToTable(string[] columnCollection, char delimiter, ref DataTable dt)
{
string[] columns = columnCollection[0].Split(delimiter);
foreach (string columnName in columns)
{
DataColumn dc = new DataColumn(columnName, typeof(string));
dt.Columns.Add(dc);
}
}
}
now to show the this DataTable to your grid view you just need to call as below
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt");
for text file like -
fname, sname, age
deepak, sharma, 23
Gaurav, sharma, 32
Alok, Kumar, 33
as you have not specified the delimiter char it will use ,
by default else you have to specified if have any other like
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt", '|');
for text file like -
fname| sname| age
deepak| sharma| 23
Gaurav| sharma| 32
Alok| Kumar| 33
it works like charm,
http://mytactics.blogspot.com/2014/11/show-delimiter-text-file-data-to.html