Search code examples
c#.netdatatabledatarowdatacolumn

Copying DataRow into new DataTable, with appropriate types from original DataTable


Consider a DataTable, of which a subset is to be copied into a new DataTable. The subset is a certain number of rows, up to a certain index. Currently, it is being done with the following code:

DataTable toDisplay = new DataTable();
// dataSource is the original DataTable
foreach (DataColumn col in dataSource.Columns)
    toDisplay.Columns.Add(new DataColumn(col.ColumnName, col.GetType()));

for (int i = 0; i < maxIndex; i++)
{
    var index = i;
    var currentRow = dataSoure.Rows[index];

    object[] currentRowItems = currentRow.ItemArray; // this is the problematic line
    toDisplay.Rows.Add(currentRowItems);
}

The problem with this approach is that the rows in the resulting table don't have the specific types from the original table. How can this be achieved?


Solution

  • You can use Clone:

    Clones the structure of the DataTable, including all DataTable schemas and constraints.

    Therefore you can simply do that as follows:

    DataTable toDisplay = dataSource.Clone();
    
    for (int i = 0; i < maxIndex; i++)
    {
        var index = i;
        var currentRow = dataSource.Rows[index];
        
        toDisplay.ImportRow(currentRow);
    }