TM

TM

  • NA
  • 1
  • 4.6k

Reading and viewing a .csv, using DataRow and itemArray

Jan 22 2013 2:06 PM
Hello everyone,

I am new in C# and I am trying to read data from a .csv file. I have a simple file of the form:

aaa,bbb,ccc
ddd,eee,fff

The goal is to show it in a DataGridView.

For this I decided to use a DataTable as I am interested in analysing some numerical values eventually.

I make a loop, split the string of each row at ',' forming a string array, creating a new row that is to be filled in by the string array and finally assigning the new row to the dataTable.

However, the itemArray command creates a problem. If I run the program without including <row.ItemArray = fields;> I get, as expected, the correct number of rows and columns in the dataGridView. When I include it, though, windows throws a "not working" error.

As far as I understand, .itemArray takes a string array and creates columns for each array element in DataRow.


Find my code below...


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

                  string csvToOpen = @"C:\Users\TM\Desktop\csvTest\sample.txt";
                  string[] csvRows = File.ReadAllLines(csvToOpen);

                  DataTable dataOut = new DataTable();

                  foreach (string csvRow in csvRows)
                  {
                  string[] fields = csvRow.Split(',');
                  DataRow row = dataOut.NewRow();
                  row.ItemArray = fields;
                  dataOut.Rows.Add(row);
                  }

                  dataGridView1.DataSource = dataOut;

            }
      }
}



Can anyone spot where the mistake is?

Thanks a lot.

Answers (1)