Simple way to convert datarow array to datatable
Asked Answered
Q

15

112

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

Quent answered 23/1, 2010 at 7:40 Comment(0)
T
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.

Thermidor answered 23/1, 2010 at 8:40 Comment(4)
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;Luce
+1 I prefer this rather than rowArray.CopyToDataTable(); because this keeps table schema and is not replacing it with new table object!Forestaysail
Very good ! But I would Suggest to clone the DataTable before the foreach. It copies the format of the DataTable: newDataTable = oldDataTable.clone();Towny
Hint: Your datatable must have columns created or it will not fill correctly.Sap
D
216

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)

Dulcy answered 10/12, 2010 at 12:28 Comment(5)
From where did you get copyToDataTable() ? I didn't find it in .net 2.0Stomodaeum
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 doesntChurchgoer
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.Phrenology
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)Keys
Remember to add System.Data.DataSetExtensions Assembly in the ReferencesLineage
T
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.

Thermidor answered 23/1, 2010 at 8:40 Comment(4)
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;Luce
+1 I prefer this rather than rowArray.CopyToDataTable(); because this keeps table schema and is not replacing it with new table object!Forestaysail
Very good ! But I would Suggest to clone the DataTable before the foreach. It copies the format of the DataTable: newDataTable = oldDataTable.clone();Towny
Hint: Your datatable must have columns created or it will not fill correctly.Sap
L
12
DataTable dt = new DataTable(); 

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

dt.Rows.Add(dr);
Latea answered 23/1, 2010 at 8:2 Comment(6)
I already tried like that.. Error occurs something like "Input array is longer than the number of columns in this table."Quent
AS Jay pointed out, Make sure your dataTable has the same schema as the DataRows in your DataRow arrayLatea
Yes.. I tried. I used Datatable1=datatable2.Clone(); Now it is working... Thank you :-)Quent
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.Mnemonics
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 <System.Data.DataRow> 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 columnInconclusive
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.Talesman
A
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");
Amerigo answered 11/8, 2011 at 11:56 Comment(0)
C
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());
Countermarch answered 20/5, 2014 at 8:23 Comment(0)
P
6
DataTable Assetdaterow =
    (
        from s in dtResourceTable.AsEnumerable()
        where s.Field<DateTime>("Date") == Convert.ToDateTime(AssetDate)
        select s
    ).CopyToDataTable();
Petition answered 27/9, 2018 at 11:31 Comment(0)
C
5
DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();
Caprine answered 23/7, 2012 at 19:7 Comment(0)
A
5
DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{ 
    dt.ImportRow(dr);
}   
Athanor answered 23/10, 2012 at 17:59 Comment(0)
K
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()
Koopman answered 23/8, 2016 at 16:16 Comment(0)
C
3

You could use System.Linq like this:

if (dataRows != null && dataRows.Length > 0)
{
   dataTable = dataRows.AsEnumerable().CopyToDataTable();
}
Covenanter answered 27/3, 2017 at 17:7 Comment(0)
E
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);
} 
Elf answered 29/6, 2011 at 6:21 Comment(0)
S
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
Sap answered 3/10, 2014 at 14:51 Comment(0)
W
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);
}
Wrack answered 4/8, 2019 at 14:57 Comment(0)
M
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);
}
Modred answered 15/2, 2018 at 9:28 Comment(0)
C
0
  public static void AddRange(this DataColumnCollection @this, params string[] columns)
        {
            foreach (string column in columns)
            {
                @this.Add(column);
            }
        }
        public static DataTable ConvertEnumerableRowCollectionToDataTable(EnumerableRowCollection<DataRow> drs, string[] columns)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(columns);
            foreach (DataRow dr in drs)
            {

                dt.ImportRow(dr);
            }

            return dt;
        }
Caribou answered 1/12, 2023 at 13:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.