Exporting Data to txt file using C#
Posted by Syed Shakeer Hussiain P
under Windows Forms
category on 5/30/2009
for Intermediate level | Views : 69643
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)
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.Value.ToString() + "\t" + dataGridView1.Rows[i].Cells.Value.ToString() + "\t" + dataGridView1.Rows[i].Cells.Value.ToString());
sw.Close(); //Don't Forget Close the TextWriter Object(sw)
MessageBox.Show("Data Successfully Exported");
In above code
Cells is first column in datagridview
Cells is second column in datagridview
Cells 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.
About the Author