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...
C#
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.
Akkiraju IvaturiRank #474 · 5.2K pointsPosted Jan 22, 2013, 9:34 AM EST
DataTable dataIOut = new DataTable();
dataOut.Columns.Add("Column1",typeof(string));
dataOut.Columns.Add("Column2", typeof(string));
dataOut.Columns.Add("Column3", typeof(string));
If you are not sure of number of columns to be added in the DataTable, find the length of the string[] fields in your code and dynamically create the number of columns as below:
if(csvRows.Length>0)
{
string[] fields = csvRows[0].Split(',');
for(int i=0;i<fields.length;i++)
dataOut.Columns.Add("Column"+i.ToString(), typeof(string));
}
And then loop through csvRows and assign data to DataTable.
Let me know if you have any questions.