简体   繁体   中英

DataTable adding column doesn't add row?

I need a bit of a steer on this DataTable concept. I'm storing data in a DataTable which I initialise by first adding a column like so:

DataTable outputData = new DataTable();
outputData.Columns.Add("Reference/Group");

Now if I write this out to a CSV file (using my own class), I get what you'd expect, a view in spreadsheet software like:

             A
 1    Reference/Group

Yet when I go on in my script to assume that row 1 exists (by referencing outputData.Rows[0] ) I get:

Exception: There is no row at position 0.

However if I try to add a row with the above content, it complains there's no column. If I specify the column then add a row, I can reference Rows[0] but by then I've got TWO rows like:

             A
 1    Reference/Group
 2    Some new row

What's the correct approach here and what is the reason for this behaviour?

You should use

outputData.Columns[0].ColumnName

instead of

outputData.Rows[0]

Because outputData.Columns.Add("Reference/Group"); will not generate new row for you. And you are using column name for A1 cell, not row data

All this says is that your custom "export" code displays column name in first CSV row. It has nothing to do with the actual data inside DataTable . There are in fact 0 rows in Your table before you insert any of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM