Exporting Data to txt file using C#

Syedshakeer
Posted by in Windows Forms category on for Intermediate level | Views : 100006 red flag

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.


 

Page copy protected against web site content infringement by Copyscape

About the Author

Syedshakeer
Full Name: Syed Shakeer Hussiain P
Member Level:
Member Status: Member
Member Since: 2/5/2009 3:12:18 AM
Country: India
Syed Shakeer Hussain
http://www.dotnetfunda.com
Shakeer Hussain has completed his Master of Computer Applications degree from Deccan College of engg and technology of Osmania University.He is a MVM of www.dotnetspider.com.He has good experience in the areas of ASP.NET, C#.NET, VB.NET, SQL SERVER 2000/2005 and Windows Mobile. He has worked in Windows Mobile,Web Applicatin and ERP projects.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)