将DataReader 转为 DataTable

/// <summary>
    /// 将DataReader 转为 DataTable
    /// </summary>
    /// <param name="DataReader">OleDbDataReader</param>
    protected DataTable ConvertDataReaderToDataTable(OleDbDataReader reader)
    {
        DataTable objDataTable = new DataTable("TmpDataTable");
        try
        {
            int intFieldCount = reader.FieldCount;//获取当前行中的列数;
            for (int intCounter = 0; intCounter <= intFieldCount - 1; intCounter++)
            {
                objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter));
            }
            //populate   datatable  
            objDataTable.BeginLoadData();
            //object[]   objValues   =   new   object[intFieldCount   -1];  
            object[] objValues = new object[intFieldCount];
            while (reader.Read())
            {
                reader.GetValues(objValues);
                objDataTable.LoadDataRow(objValues, true);
            }
            reader.Close();
            objDataTable.EndLoadData();
            return objDataTable;
        }
        catch (Exception ex)
        {
            throw new Exception("转换出错出错!", ex);
        }
    }

你可能感兴趣的:(Datatable)