Convert datatable to datareader

I know this is old, but the answers here seem to have missed the point of the OPs question.

DataTables have a method called CreateDataReader which will allow you to convert a DataTable to a DbDataReader object. In this case a DataTableReader.

DataTable table = new DataTable(); 
//Fill table with data 
//table = YourGetDataMethod(); 
DataTableReader reader = table.CreateDataReader();

I should point out that this will not increase performance since you should be using one or the other.

Here are some more resources on the matter:

  • DataReader Vs DataTable
  • Is datareader quicker than dataset when populating a datatable?

For example

public DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
    DataTable datatable = new DataTable();
    DataTable schemaTable = dataReader.GetSchemaTable();

    try
    {

        foreach (DataRow myRow in schemaTable.Rows)
        {
            DataColumn myDataColumn = new DataColumn();
            myDataColumn.DataType = myRow.GetType();
            myDataColumn.ColumnName = myRow[0].ToString();
            datatable.Columns.Add(myDataColumn);
        }
        while (dataReader.Read())
        {
            DataRow myDataRow = datatable.NewRow();
            for (int i = 0; i < schemaTable.Rows.Count; i++)
            {
                myDataRow[i] = dataReader[i].ToString();
            }
            datatable.Rows.Add(myDataRow);
            myDataRow = null;
        }
        schemaTable = null;
        return datatable;
    }
    catch (Exception ex)
    {
        Error.Log(ex.ToString());
        return datatable;
    }
}

Tags:

C#

Ado.Net