Simple way to convert datarow array to datatable

Developer404 picture Developer404 · Jan 23, 2010 · Viewed 335.5k times · Source

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

Answer

joe picture joe · Dec 10, 2010

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)