Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello
i want to load a text file in this file first row is "Column Header" and other data row and data Separator with "," how i can load a text file into datagrid view using c# window application. Plz Reply me

Thanks
Posted

Hi,
You can iterate through your file and then add them to a DataTable. then, you can bind the DataTable to your DataGridView.
A post to read a text file:
http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx[^]
A post about DataTable:
http://www.dotnetperls.com/datatable[^]

I hope it helps,
Cheers
 
Share this answer
 
Comments
VJ Reddy 11-Apr-12 13:24pm    
Good links. 5!
Reza Ahmadi 11-Apr-12 13:39pm    
Thanks!
The data contained in the text file in the format specified in the question can be read into a DataTable and the DataTable can be bound to a DataGridView using the following code
C#
void Main()
{
	Form form1 = new Form();
	DataGridView dataGridView1 = new DataGridView();
	dataGridView1.Dock= DockStyle.Fill;

        //Read the data from text file
	string[] textData = System.IO.File.ReadAllLines(dataFileName);
	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=1; i < textdata.length; i++)
            dataTable1.Rows.Add(textData[i].Split(','));

        //Set the DataSource of DataGridView to the DataTable
	dataGridView1.DataSource = dataTable1;
	form1.Controls.Add(dataGridView1);
	form1.ShowDialog();
}
 
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