C# – Import data from text file and display in datagrid


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 respective columns.

There is column delimiters and row delimiters are present in text file.I want to display the data in a data grid in which header will be the column name and all the data will be display under each column.

I have successfully taken the data from the file. The problem is the file may different for each time and the number of columns may vary. So I can not use a predefined class for it.I wanted to create a class for run time and add the properties at run time and to display the list to data grid. How can I complete this task ?

Best Solution

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];

    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));


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,

enter image description here


Related Question