0

I've got a DataTable dTable which hold several columns and rows.

I'm writing a function to shuffle the rows, therefore I want to copy the rows (with data) to a List. which I do with the following code:

        List<DataRow> rows = new List<DataRow>(dTable.Rows.Count);
        int count = 0; 
        foreach (DataRow rowname in dTable.Rows)
        {
            rows.Add(dTable.NewRow());
            rows[count].BeginEdit();
            rows[count] = (rowname);
        } 

Now I want to clear the DataTable dTable and randomly add the rows back to the DataTable, however if I add dTable.Clear(), the information in the rows in the List is also cleared, how do I remove the rows from the `DataTable' without loosing data in the List?

2pietjuh2
  • 879
  • 2
  • 13
  • 29
  • 1
    I think you have a fellow questioner here: http://stackoverflow.com/questions/12025012/c-sharp-simple-way-to-copy-or-clone-a-datarow – Kat Jul 30 '14 at 13:57

2 Answers2

0

Hope I explain the following correctly.

Remember when you are taking a value from one place and storing it in another you aren't creating a new instance of it but pointing back to the original data. So when you are adding your row to a list it's pointing back to your datatable which you then clear so your list will now not contain your row information.

This works but there may be another way. Didn't spend a lot of time looking into it.

//temp table with row struct as not to point back to the original
//datatable that we will clear so we will just clone it.
DataTable tempDT = dt.Clone();

List<DataRow> rows = new List<DataRow>();

foreach (DataRow row in dt.Rows)
{
    DataRow copy = tempDT.NewRow();
    copy.ItemArray = (object[])row.ItemArray.Clone();
    rows.Add(copy);
}

dt.Clear();
Tsukasa
  • 6,342
  • 16
  • 64
  • 96
0

I think the major problem is that dTable.Clear() also removes the columns. Try using dTable.Rows.Clear() instead.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57