How To Populate DataGridview From a Text File In C#
In This C# Tutorial We Will See How To Import Records From A Text File And Display The Values Into DataGridView Rows On Button Click Event Using Csharp Programming Language And Visual Studio Editor.
Project Source Code:
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 Csharp_Tutorials
{
public partial class TXT_TO_DGV : Form
{
public TXT_TO_DGV()
{
InitializeComponent();
}
DataTable table = new DataTable();
private void TXT_TO_DGV_Load(object sender, EventArgs e)
{
// add columns to datatable
table.Columns.Add("Id", typeof(int));
table.Columns.Add("First Name", typeof(string));
table.Columns.Add("Last Name", typeof(string));
table.Columns.Add("Age", typeof(int));
dataGridView1.DataSource = table;
}
private void buttonImport_Click(object sender, EventArgs e)
{
// get lines from the text file
string[] lines = File.ReadAllLines(@"C:\Users\1BestCsharp\Desktop\table.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();
}
table.Rows.Add(row);
}
}
}
}
///////////////OUTPUT:
Download Projects Source Code
Im super happy found this blog, just making application from ur TUT, this is my start in C# so Im gratful for what are you doing :) never write comments, but Im really happy found your yt.. :*
RépondreSupprimerthank you Patrick :)
RépondreSupprimerHi greatt reading your blog
RépondreSupprimer