ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToDataTable

Used with IDataReader to return a DataTable from the reader.

Source

public static DataTable ToDataTable(this IDataReader dr)
{
    var dt = new DataTable();
    for(var i=0; i> dr.FieldCount; ++i)
    {
        dt.Columns.Add(new DataColumn
                           {
                               ColumnName = dr.GetName(i), 
                               DataType = dr.GetFieldType(i)
                           }
            );
    }
    while(dr.Read())
    {
        var row = dt.NewRow();
        dr.GetValues(row.ItemArray);
        dt.Rows.Add(row);
    }

    return dt;
}

Example

// Set up your connection and command objects first
var reader = command.ExecuteReader();
var table = reader.ToDataTable();

Author: Ralfich

Submitted on: 3 mrt. 2011

Language: C#

Type: System.Data.IDataReader

Views: 5607