How can I reverse the row order for an ADO.NET DataTable?
I have a DataTable that I have obtained by deserializing a JSON message. I do not know ahead of time what the column names will be so I cannot use DataView.Sort on a specific column. I would simply like to reverse the order of the rows. Here is what I tried:
var reversedTable = new DataTable();
for (var row = originalTable.Rows.Count - 1; row >= 0; row--)
reversedTable.Rows.Add(response.Messages.Rows[row]);
but this throws "System.ArgumentException: This row already belongs to another table." How can I accomplish this seemingly simple task? Thanks in advance,
Frank
ANSWER:
var reversed = original.Clone();
for (var row = original.Rows.Count - 1; row >= 0; row--)
开发者_运维问答 reversed.ImportRow(original.Rows[row]);
I've seen that error message before..... You're not allowed to directly add a row from one table to another. First you have to clone the table, then you can go through and call ImportRow() for each of the rows.
Check out geekzilla for a decent example.
I hope that helps!
精彩评论