5 November 2014

Show delimiter Text file data to DataGridView

Hi All,

Lets see how to show the delimiter text file in DataGridView in C#.  Lot of use face the problem when we have CSV or any other delimiter text file and asked to show it as table in C# DataGridView.

As one user asked at Stackoverflow


You can have to copy paste the following code and ready to go..

using System.Data;
using System.IO;


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)
 {
     bool IsHeaderSet = false;

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

 }

}

Thats all.. ready to use.. Now let me tell you how to bind this with DataGridView just call

// if | is delimiter char
//fname| sname| age
//deepak| sharma| 23
//Gaurav| sharma| 32
//Alok| Kumar| 33
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt", '|');


//if comma , is delimiter char like - 
//fname, sname, age
//deepak, sharma, 23
//Gaurav, sharma, 32
//Alok, Kumar, 33
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt");


if pipeline(|) is delimiter character else pass what else it is.  Default delimiter char is common(,) so in case of (,) no need to even pass it.

It works like charm. :)




Happy Coding.. and Sharing.. :)

No comments:

Post a Comment