Windows Forms: How to read .csv file in C#

How to read CSV file into datatable and show data in DataGridView using c#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadCsvFile" and then click OK

c# read csv fileStep 2: Design your form as below

read csv file in c#

Step 3: Add code to button click event handler as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReadCsvFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Read csv file
        public DataTable ReadCsv(string fileName)
        {
            DataTable dt = new DataTable("Data");
            using(OleDbConnection cn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\""+
                Path.GetDirectoryName(fileName) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)';"))
            {
                //Execute select query
                using (OleDbCommand cmd = new OleDbCommand(string.Format("select *from [{0}]", new FileInfo(fileName).Name), cn))
                {
                    cn.Open();
                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                }
            }
            return dt;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                //Open file dialog, allows you to select a csv file
                using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true, Multiselect = false })
                {
                    if (ofd.ShowDialog() == DialogResult.OK)
                        dataGridView.DataSource = ReadCsv(ofd.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

VIDEO TUTORIALS