How to Export Data From Datagridview to Text File in C#
Export Data From Datagridview to Text File in C#
In this tutorial, we will see the How to export data from datagridview to text file in c# and load a text file into datagridview in window application in c# using the DataTable, TextWriter, StreamWriter, ReadAllLines.
Source Code For Export Data From Datagridview to Text File in C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace exportdatagridview { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { this.Close(); } DataTable table1 = new DataTable(); DataTable table2 = new DataTable(); private void Form1_Load(object sender, EventArgs e) { table1.Columns.Add("ID", typeof(int)); table1.Columns.Add("First Name", typeof(string)); table1.Columns.Add("Last Name", typeof(string)); table1.Columns.Add("Age", typeof(int)); table1.Rows.Add(1, "First A", "Last A", 10); table1.Rows.Add(2, "First B", "Last B", 20); table1.Rows.Add(3, "First C", "Last C", 30); table1.Rows.Add(4, "First D", "Last D", 40); table1.Rows.Add(5, "First E", "Last E", 50); table1.Rows.Add(6, "First F", "Last F", 60); table1.Rows.Add(7, "First G", "Last G", 70); table1.Rows.Add(8, "First H", "Last H", 80); table1.Rows.Add(9, "First I", "Last I", 90); // populate datagridview with some data using datatable dataGridViewExport.DataSource = table1; } private void button1_Click(object sender, EventArgs e) { TextWriter writer = new StreamWriter(@"D:\Demo\table1.txt"); for (int i = 0; i < dataGridViewExport.Rows.Count - 1; i++) // rows { for (int j = 0; j < dataGridViewExport.Columns.Count; j++) // columns { if (j == dataGridViewExport.Columns.Count - 1) // if last column { writer.Write("\t" + dataGridViewExport.Rows[i].Cells[j].Value.ToString()); } else writer.Write("\t" + dataGridViewExport.Rows[i].Cells[j].Value.ToString() + "\t" + "|"); } writer.WriteLine(""); } writer.Close(); MessageBox.Show("Data Exported"); } } }
Open Source Code
Read More>>
- How to Generate and Validate a Software License Key using C#
- Calculator program in C# Windows Application with Source code
- Notepad in VB.net with Full Source Code | Trickcode
- SaveFileDialog Control In C#-Trickcode
- C#- FontDialog Control-Trickcode
- How To Crystal Report option that directly print to the printer in the network
Post A Comment:
0 comments: