Click here to Skip to main content
15,881,593 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all

Please tell me how to bind text file data to a datagrid in c# windows application.

below is the code i tried but its executing without error but not giving any result
C#
DataGridView dataGridView1 = new DataGridView();
dataGridView1.Dock = DockStyle.Fill;

//Read the data from text file
string[] textData = System.IO.File.ReadAllLines(@"D:\\Display.txt");
string[] headers = textData[0].Split(',');

//Create and populate DataTable
DataTable dataTable1 = new DataTable();
foreach (string header in headers)
 dataTable1.Columns.Add(header, typeof(string), null);
for (int i = 0; i < textData.Length; i++)
 dataTable1.Rows.Add(textData[i]);

//Set the DataSource of DataGridView to the DataTable
dataGridView1.DataSource = dataTable1;

Please tell me what is the problem or any other solution.
Posted
Updated 4-Nov-14 1:23am
v2

1 solution

You need to add newly create dataGridView1 to your form.
C#
dataGridView1.DataSource = dataTable1;
this.Controls.Add(dataGridView1);


I'm not sure how your text file data arranged, but it seems you are doing it wrong way. for example if you have text file like below
Column1,Column2
data11,data12
data21,data22

then your code should be like below
C#
DataTable dataTable1 = new DataTable();
foreach (string header in headers)
    dataTable1.Columns.Add(header, typeof(string), null);
for (int i = 1; i < textData.Length; i++)
    dataTable1.Rows.Add(textData[i].Split(','));

1. note that, adding data started from index 1 (second row)
2. when adding row data you can split and set values for each column, otherwise line content will assign to first column only.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900