111

I want to convert a DataRow array into DataTable ... What is the simplest way to do this?

Adam Miller
  • 767
  • 1
  • 9
  • 22
Developer404
  • 5,716
  • 16
  • 64
  • 102

14 Answers14

214

For .Net Framework 3.5+

DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();

But if there is no rows in the array, it can cause the errors such as The source contains no DataRows. Therefore, if you decide to use this method CopyToDataTable(), you should check the array to know it has datarows or not.

if (dr.Length > 0)
    DataTable dt1 = dr.CopyToDataTable();

Reference available at MSDN: DataTableExtensions.CopyToDataTable Method (IEnumerable)

Ken Kin
  • 4,503
  • 3
  • 38
  • 76
joe
  • 2,422
  • 3
  • 18
  • 16
  • 1
    From where did you get `copyToDataTable()` ? I didn't find it in .net 2.0 – SMUsamaShah Sep 17 '11 at 11:41
  • 11
    This should be marked as a right answer since `copyToDataTable()` method creates a perfect copy of the columns of the selected rows, whilst `datatable.ImportRow(row)` method doesnt – Dante Jun 27 '12 at 19:28
  • 5
    this method isn't good if the table already has rows in it as this replace whatever already there. If table empty to start with it's fine. – Franck Mar 18 '14 at 12:19
  • 5
    I prefer this method as long as .Net functions are optimized. Don't forget to add the reference to System.Data.DataSetExtensions in your project so you won't get frustated asking yourself why this method is missing (like me) – Broken_Window Jul 08 '14 at 14:41
  • Remember to add System.Data.DataSetExtensions Assembly in the References – Vagner Gon Sep 21 '17 at 14:41
98

Why not iterate through your DataRow array and add (using DataRow.ImportRow, if necessary, to get a copy of the DataRow), something like:

foreach (DataRow row in rowArray) {
   dataTable.ImportRow(row);
}

Make sure your dataTable has the same schema as the DataRows in your DataRow array.

Jay Riggs
  • 53,046
  • 9
  • 139
  • 151
  • 1
    This technique is helpful if you get the error message "An invalid data source is being used for MyControl. A valid data source must implement either IListSource or IEnumerable" when trying to bind a DataRow directly to the DataSource property of a control. Here's how to do it: `DataTable dataTable = new DataTable(); dataTable.ImportRow(dataRow); MyControl.DataSource = dataTable;` – humbads Oct 03 '12 at 15:44
  • +1 I prefer this rather than `rowArray.CopyToDataTable();` because this keeps table schema and is not replacing it with new table object! – Mojtaba Rezaeian Jan 15 '16 at 18:16
  • 9
    Very good ! But I would Suggest to clone the DataTable before the foreach. It copies the format of the DataTable: newDataTable = oldDataTable.clone(); – Whiplash Oct 03 '16 at 18:08
  • 3
    Hint: Your datatable must have columns created or it will not fill correctly. – logixologist Jan 03 '17 at 16:07
12
DataTable dt = new DataTable(); 

DataRow[] dr = (DataTable)dsData.Tables[0].Select("Some Criteria");

dt.Rows.Add(dr);
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 2
    I already tried like that.. Error occurs something like "Input array is longer than the number of columns in this table." – Developer404 Jan 23 '10 at 08:55
  • AS Jay pointed out, Make sure your dataTable has the same schema as the DataRows in your DataRow array – Mitch Wheat Jan 23 '10 at 09:06
  • 1
    Yes.. I tried. I used Datatable1=datatable2.Clone(); Now it is working... Thank you :-) – Developer404 Jan 23 '10 at 09:17
  • I tried this with a row array and it didn't work. For each row in the row array, I created a new row, copied the ItemArray property from the original row and then the add worked. – Steve Feb 02 '10 at 14:08
  • 1
    This does not seem to work in .NET Framework 4.0 with the sample as posted, nor with "dt" being cloned from dstata.tables[0]. @joe's answer did end up working for my purposes. No-Clone Version error: "`Input array is longer than the number of columns in this table.`". With-Clone Version Error: "`Unable to cast object of type 'System.Data.DataRow' to type 'System.IConvertible'.Couldn't store in StoreOrder Column. Expected type is Int64.`" Note: `StoreOrder` is the first column in the table schema. Seems it's trying to jam entire datarow into that first column – Brian Webster Dec 16 '11 at 00:06
  • It tries to make ONE datarow, using it's input as "The array of values that are used to create the new row". Not good by any measure. – Eugene Ryabtsev Mar 19 '14 at 10:41
11

Simple way is:

// dtData is DataTable that contain data
DataTable dt = dtData.Select("Condition=1").CopyToDataTable();

// or existing typed DataTable dt
dt.Merge(dtData.Select("Condition=1").CopyToDataTable());
Zolfaghari
  • 1,259
  • 1
  • 15
  • 14
11

Another way is to use a DataView

// Create a DataTable
DataTable table = new DataTable()
...

// Filter and Sort expressions
string expression = "[Birth Year] >= 1983"; 
string sortOrder = "[Birth Year] ASC";

// Create a DataView using the table as its source and the filter and sort expressions
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows);

// Convert the DataView to a DataTable
DataTable new_table = dv.ToTable("NewTableName");
ilans
  • 2,537
  • 1
  • 28
  • 29
6
DataTable Assetdaterow =
    (
        from s in dtResourceTable.AsEnumerable()
        where s.Field<DateTime>("Date") == Convert.ToDateTime(AssetDate)
        select s
    ).CopyToDataTable();
Han
  • 3,052
  • 2
  • 22
  • 31
Rajenthiran T
  • 77
  • 1
  • 6
5
DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Miriam
  • 59
  • 1
  • 3
5
DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{ 
    dt.ImportRow(dr);
}   
CMedina
  • 4,034
  • 3
  • 24
  • 39
user1036202
  • 51
  • 1
  • 1
4

.Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method

For datarow array just use .CopyToDataTable() and it will return datatable.

For single datarow use

new DataRow[] { myDataRow }.CopyToDataTable()
3

You could use System.Linq like this:

if (dataRows != null && dataRows.Length > 0)
{
   dataTable = dataRows.AsEnumerable().CopyToDataTable();
}
2

Here is the solution. It should work fine.

DataTable dt = new DataTable();
dt = dsData.Tables[0].Clone();
DataRows[] drResults = dsData.Tables[0].Select("ColName = 'criteria');

foreach(DataRow dr in drResults)
{
    object[] row = dr.ItemArray;
    dt.Rows.Add(row);
} 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
zaib shah
  • 21
  • 1
1

Incase anyone needs it in VB.NET:

Dim dataRow as DataRow
Dim yourNewDataTable as new datatable
For Each dataRow In yourArray
     yourNewDataTable.ImportRow(dataRow)
Next
logixologist
  • 3,694
  • 4
  • 28
  • 46
1

You need to clone the structure of Data table first then import rows using for loop

DataTable dataTable =dtExisting.Clone();
foreach (DataRow row in rowArray) {
   dataTable.ImportRow(row);
}
HK boy
  • 1,398
  • 11
  • 17
  • 25
0
DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
 DataRow AddNewRow = dataTable.AddNewRow();
 AddNewRow.ItemArray = dr.ItemArray;
 dataTable.Rows.Add(AddNewRow);
}