C# Import Text File Data To DataGridview

How To Populate DataGridview From a Text File In C#

display txt file text to a datagridview using 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:

Import Text File Text To DataGridview Using C#




Share this

Related Posts

Previous
Next Post »

3 comments

comments
13 novembre 2019 à 20:21 delete

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.. :*

Reply
avatar
10 janvier 2022 à 17:31 delete

Hi greatt reading your blog

Reply
avatar