How To Get And Set DataGridView Data To Txt File Text Using C#
In This C# Tutorial We Will See How To Import Records From A Text File And Display The Values Into DataGridView, and Export DataGridView Rows Data To a Txt File Using DataTable, TextWriter, StreamWriter, ReadAllLines In Csharp Programming Language And Visual Studio Editor.
PART 1
PART 2
Project Source Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Csharp_Tutorials
{
public partial class Import_Export_DGV_to_TXT_File : Form
{
public Import_Export_DGV_to_TXT_File()
{
InitializeComponent();
}
DataTable table1 = new DataTable();
DataTable table2 = new DataTable();
private void Import_Export_DGV_to_TXT_File_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;
table2.Columns.Add("ID", typeof(int));
table2.Columns.Add("First Name", typeof(string));
table2.Columns.Add("Last Name", typeof(string));
table2.Columns.Add("Age", typeof(int));
dataGridViewImport.DataSource = table2;
}
// button export
private void buttonExport_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter(@"C:\Users\1BestCsharp\Desktop\table2.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");
}
// button import
private void buttonImport_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(@"C:\Users\1BestCsharp\Desktop\table2.txt");
string[] values;
for (int i = 0; i < lines.Length; i++)
{
values = lines[i].ToString().Split('|');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}
table2.Rows.Add(row);
}
}
}
}
///////////////OUTPUT:
Download Projects Source Code