.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Exporting Data to txt file using C#

Posted By:Syed Shakeer Hussain       Posted Date: May 26, 2009    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  

In this Article i am going to explain you how to Export a DataGridView(Windows) data to a Text File(.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 datagideview 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.

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend