轻松将DataReader转换成DataTable
在程序开发中,有时候需要用将DataReader转换成DataTable,我这里有一段代码供新手参考!
/// <summary>
/// 把DataReader转换成DataTable
/// </summary>
/// <param name="vDataReader">预转换的DataReader</param>
/// <returns>DataTable</returns>
public DataTable[] DataReaderToDataTables(OleDbDataReader vDataReader)
{
ArrayList TableArrayList = new ArrayList();
do
{
DataTable NewDataTable = new DataTable();
DataTable TableSchema = vDataReader.GetSchemaTable();
for(int i=1;i<=TableSchema.Rows.Count;i++)
NewDataTable.Columns.Add(TableSchema.Rows[i-1]〔"ColumnName"〕.ToString(), System.Type.GetType(TableSchema.Rows[i-1]〔"DataType"〕.ToString()));
while(vDataReader.Read()==true)
{
DataRow NewDataRow = NewDataTable.NewRow();
for(int i=1;i<=vDataReader.FieldCount;i++)
NewDataRow[i-1] = vDataReader[i-1];
NewDataTable.Rows.Add(NewDataRow);
}
TableArrayList.Add(NewDataTable);
}while(vDataReader.NextResult()==true);
DataTable[] ReturnDataTable = new DataTable[TableArrayList.Count];
for(int i=1;i<=TableArrayList.Count;i++)
ReturnDataTable[i-1] = (DataTable)TableArrayList[i-1];
return ReturnDataTable;
}
/// 把DataReader转换成DataTable
/// </summary>
/// <param name="vDataReader">预转换的DataReader</param>
/// <returns>DataTable</returns>
public DataTable[] DataReaderToDataTables(OleDbDataReader vDataReader)
{
ArrayList TableArrayList = new ArrayList();
do
{
DataTable NewDataTable = new DataTable();
DataTable TableSchema = vDataReader.GetSchemaTable();
for(int i=1;i<=TableSchema.Rows.Count;i++)
NewDataTable.Columns.Add(TableSchema.Rows[i-1]〔"ColumnName"〕.ToString(), System.Type.GetType(TableSchema.Rows[i-1]〔"DataType"〕.ToString()));
while(vDataReader.Read()==true)
{
DataRow NewDataRow = NewDataTable.NewRow();
for(int i=1;i<=vDataReader.FieldCount;i++)
NewDataRow[i-1] = vDataReader[i-1];
NewDataTable.Rows.Add(NewDataRow);
}
TableArrayList.Add(NewDataTable);
}while(vDataReader.NextResult()==true);
DataTable[] ReturnDataTable = new DataTable[TableArrayList.Count];
for(int i=1;i<=TableArrayList.Count;i++)
ReturnDataTable[i-1] = (DataTable)TableArrayList[i-1];
return ReturnDataTable;
}