把dataReader转化为dataTable.下面的代码就能实现这个功能。
public static DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
//把那个DataReader转化成DataTable。
DataTable datatable = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();
//动态添加列
try
{
foreach (DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = myRow[0].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];
Type type = dataReader[i].GetType();
switch (type.Name)
{
case "String":
myDataRow[i] = (string)dataReader[i];
break;
case "Int16":
myDataRow[i] = (short)dataReader[i];
break;
case "Int32":
myDataRow[i] = (int)dataReader[i];
break;
case "Int64":
myDataRow[i] = (long)dataReader[i];
break;
case "DateTime":
myDataRow[i] = (DateTime)dataReader[i];
break;
case "Decimal":
myDataRow[i] = (decimal)dataReader[i];
break;
case "Char":
myDataRow[i] = (char)dataReader[i];
break;
case "Double":
myDataRow[i] = (double)dataReader[i];
break;
default:
myDataRow[i] = dataReader[i];
break;
}
}
datatable.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
dataReader.Close();
return datatable;
}
catch (Exception ex)
{
Error.Log(ex.ToString());
throw new Exception("转换出错出错!", ex);
}
}