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
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.
Akkiraju IvaturiPosted Jan 22, 2013, 2:34 PM
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
}
And then loop through csvRows and assign data to DataTable.
Let me know if you have any questions.