![]()
Article posted by
Syedshakeer on 5/30/2009 | Views: 29108 | Category:
Windows Forms | Level: Intermediate
If you found
plagiarised (copied) or inappropriate content,
please
let us know the original source along with your correct email id (to communicate) for further action.
In this Article i am going to explain you how to Export a DataGridView(Windows) data to a TextFile(.txt)
Hi,
In this Article i am going to explain you how to Export a DataGridView(Windows) data to a TextFile(.txt) first i created a Table with a name 'emp'.it has 3 columns as 'id' number,'empname' varchar,'salary' number and i Inserted Some Data in 'emp' Table.
Next Retrive the Data in DataGridview(windows).
AfterRetreving OutPut of Datagridview as below :

What you have data, present in datagrideview that data should be export in to the txtfile.
creating a text file with a coding :-
Below line is creating a textfile with a name file11.just you have to give a path where your text file should be located.here I am saving my file in 'F Drive'.
FileStream fileStream = new FileStream(@"F:\file11.txt", FileMode.Create);
Here FileMode.Create will automatically create a textfile with a name called file11.txt in 'F drive' with a FileStream Class.
If your are using Io Streams class then you have to Import a NameSpace as Using Sytstem.Io;
Write below code in one Button
TextWriter sw = new StreamWriter(@"F:\\file11.txt");
int rowcount = dataGridView1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dataGridView1.Rows[i].Cells[0].Value.ToString() + "\t" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "\t" + dataGridView1.Rows[i].Cells[2].Value.ToString());
}
sw.Close(); //Don't Forget Close the TextWriter Object(sw)
MessageBox.Show("Data Successfully Exported");
In above code
Cells[0] is first column in datagridview
Cells[1] is second column in datagridview
Cells[2] is third column in datagridview
After Exporting Open your txt file and you can see the output :

This is the simple way Exporting Data to a textfile.Plz Give me Feed back about this Article.
If you like this article, subscribe to our
RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.
Found interesting? Add this to: