3

I have written the following code for reading data from .csv file:

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 CSVRead
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void buttonRead_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Username");
            dataTable.Columns.Add("Password");
            dataTable.Columns.Add("MachineID");
            string filePath = textBox1.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]);
            }
            dataGridView1.DataSource = dataTable;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}

Here is my CSV File data (readCSV.csv):

Username, Password, MachineID
abc, abc, 123
jkl, jkl, 789
rst, rst, 456

I have a dataGridView in my Windows Form Application (see image link below as I haven't accumulated enough reputation to post an image) and want to display data from CSV file in this grid view. This code isn't throwing any error/warning but it is simply not executing the way it should. On clicking the Find button the data is not getting displayed in the dataGridView. I am using Visual Studio 2013 Professional.

WinFormApp

Silly Me: Oops!!! The above code is working absolutely fine... I was writing my code on Remote machine and I stored my file on local machine. Also, the name of button click event was mistyped.

NOTE: The answer has been marked as accepted because its logic works too. The code written above in my question is also a working absolutely fine

Yash Saraiya
  • 1,035
  • 1
  • 20
  • 40
  • Are you checking autogeneratecolumns on DataGridView? https://msdn.microsoft.com/es-es/library/system.windows.forms.datagridview.autogeneratecolumns(v=vs.110).aspx – Jaime García Pérez Nov 03 '15 at 08:24
  • So far I haven't checked it – Yash Saraiya Nov 03 '15 at 08:26
  • `File.ReadAllLines`will read the file into an enumerable, so you can just do something like `var contents = File.ReallAllLines(path)` and get rid of the stream reader and then just loop over the `contents` and split the line there. – Stuart Grassie Nov 03 '15 at 08:27
  • Did you debug and found any problem? You might need a `dataGridView1.DataBind()` at the end. – Arghya C Nov 03 '15 at 08:27
  • CSV files are more complicated than that, for instance, what if the comma is in quotes? – Jodrell Nov 03 '15 at 08:28
  • @ArghyaC on using DataBind() i am getting the following the error `'System.Windows.Forms.DataGridView' does not contain a definition for 'DataBind' and no extension method 'DataBind' accepting a first argument of type 'System.Windows.Forms.DataGridView' could be found (are you missing a using directive or an assembly reference?)` – Yash Saraiya Nov 03 '15 at 09:02

2 Answers2

5

Here is working example to solve your problem.but before you start you should know few things while reading CVS files or excel files. For excel file always first row is the name of columns so you do not need to add columns to Data-table manually

 try
            {
                // your code here 
     string CSVFilePathName = @"path and file name";
                string[] Lines = File.ReadAllLines(CSVFilePathName);
                string[] Fields;
                Fields = Lines[0].Split(new char[] { ',' });
                int Cols = Fields.GetLength(0);
                DataTable dt = new DataTable();
                //1st row must be column names; force lower case to ensure matching later on.
                for (int i = 0; i < Cols; i++)
                    dt.Columns.Add(Fields[i].ToLower(), typeof(string));
                DataRow Row;
                for (int i = 1; i < Lines.GetLength(0); i++)
                {
                    Fields = Lines[i].Split(new char[] { ',' });
                    Row = dt.NewRow();
                    for (int f = 0; f < Cols; f++)
                        Row[f] = Fields[f];
                    dt.Rows.Add(Row);
                }
                dataGridClients.DataSource = dt;  
 }
            catch (Exception ex )
            {
                MessageBox.Show("Error is " + ex.ToString());
                throw;
            }
Mohammed Ali
  • 696
  • 3
  • 9
  • 22
  • This is not having any effect on the dataGridView (not getting any error msg or warning though) – Yash Saraiya Nov 03 '15 at 08:48
  • have you change datagrid name to follow your DG name. i have tested this code and the result is fine.regarding display error add try catch your code and exception – Mohammed Ali Nov 03 '15 at 09:23
  • My datagrid name is same as displayed in the properties window. Can you help me with Try catch code? – Yash Saraiya Nov 03 '15 at 09:26
  • 1
    here is example how to use try catch try { // your code here } catch (Exception ex ) { MessageBox.Show("Error is " + ex.ToString()); throw; } /// please check the code , already updated with try catch – Mohammed Ali Nov 03 '15 at 09:34
  • Tried your updated code with try-catch but still it is not having any effect on the dataGridView... not showing any MessageBox either – Yash Saraiya Nov 03 '15 at 09:45
  • There wasn't any error in the logic or code... I have updated how silly i was... Thanks for your efforts – Yash Saraiya Nov 03 '15 at 11:22
  • 1
    I am marking your answer as accepted because your logic works too!!! My code in the question is correct either – Yash Saraiya Nov 04 '15 at 04:59
0

First check the autogenerateColumns on dataGridView. Next check if your datatable is correcting being filled.

Check this example, can help you a lot: Faster way of reading csv to grid

Community
  • 1
  • 1
Jaime García Pérez
  • 953
  • 1
  • 10
  • 16