Wednesday, 30 January 2013

Reading Data from CSV File using C#

Step 1: Create New Project (Windows Forms Application).
Step 2: Add “System.IO” namespace.
Step 3: Create the form as follows.

Step 4: Write the following code.

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

namespace ReadingCSV
    public partial class Form1 : Form
        public Form1()

        private void buttonRead_Click(object sender, EventArgs e)
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("First Name");
            dataTable.Columns.Add("Last Name");
            string filePath = textBoxFilePath.Text;
            StreamReader streamReader = new StreamReader(filePath);
            string[] totalData = new string[File.ReadAllLines(filePath).Length];
            totalData = streamReader.ReadLine().Split(',');
            while (!streamReader.EndOfStream)
                totalData = streamReader.ReadLine().Split(',');
                dataTable.Rows.Add(totalData[0], totalData[1], totalData[2]);
            dataGridViewStudents.DataSource = dataTable;

Step 5: Output


  1. I tried to use your code in my Windows Form Application but the data from CSV file is not getting displayed in dataGridView on clicking Find button