C#: Importing CSV Content And Populating DataGridView In Windows Form App With The Content


Introduction

If you ever wondered how to read a CSV file and populate the content of the CSV onto a Datagridview of your Windows Form Application then you are in the right place.

Well, there's always a hard way to do stuff and there's an easy way. In this article, we are going to share an effective yet easy way to read CSV and display the content on a Datagridview in the form of rows and columns.

The Method

Reading The CSV File

We write a class named ReadCSV in your Windows Form application as shown:

using System.Linq;
using System.Data;
using Microsoft.VisualBasic.FileIO; // This namespace usage is important or else TextFieldParser method will lead to error
using System.IO;
 
namespace CSVApp
{
    public class  ReadCSV
    {
        public DataTable readCSV;
 
        public ReadCSV(string fileName, bool firstRowContainsFieldNames = true)
        {
            readCSV = GenerateDataTable(fileName, firstRowContainsFieldNames);
        }
 
        private static DataTable GenerateDataTable(string fileName, bool firstRowContainsFieldNames = true)
        {
            DataTable result = new  DataTable();
 
            if (fileName == "")
            {
                return result;
            }
 
            string delimiters = ",";
            string extension = Path.GetExtension(fileName);
 
            if (extension.ToLower() == "txt")
                delimiters = "\t";
            else if  (extension.ToLower() == "csv")
                delimiters = ",";
 
            using (TextFieldParser tfp = new TextFieldParser(fileName))
            {
                tfp.SetDelimiters(delimiters);
 
                // Get The Column Names
                if (!tfp.EndOfData)
                {
                    string[] fields = tfp.ReadFields();
 
                    for (int i = 0; i < fields.Count(); i++)
                    {
                        if (firstRowContainsFieldNames)
                            result.Columns.Add(fields[i]);
                        else
                            result.Columns.Add("Col" + i);
                    }
 
                    // If first line is data then add it
                    if (!firstRowContainsFieldNames)
                        result.Rows.Add(fields);
                }
 
                // Get Remaining Rows from the CSV
                while (!tfp.EndOfData)
                    result.Rows.Add(tfp.ReadFields());
            }
 
            return result;
        }
    }
}

In the aforementioned code we assume that the CSV file only contains either comma separated or tab delimited contents. And therefore in this code we check the types of delimiters used. And another benefit of this ReadCSV class is that it can also read TXT file which contains tab delimited content. 

Populate The CSV Content

Well, the heart of the logic to read and populate CSV content is ready from the preceding code. You just need to create an object and pass the path of your CSV file to that object. This will create the DataTable holding the content of the CSV and you can populate the Datagridview with this newly created DataTable by adding the DataTable as the DataSource of the Datagrid view.

The code for this is as follows:

// fileName should consist of the CSV file name with full path
    private void  LoadCSVOnDataGridView(string fileName)
        {
            try
            {
                ReadCSV csv = new  ReadCSV(fileName);
 
                try
                {
                    dataGridView.DataSource = csv.readCSV;
                }
                catch (Exception ex)
                {
                    throw new  Exception(ex.Message);
                }
            }
            catch (Exception ex)
            {
                throw new  Exception(ex.Message);
            }
        }

Once, everything is done properly you should see the CSV content on your Datagrid view in the form of rows and columns, similar to this screenshot:

See Also