首页 > 代码库 > 关于值类型与列类型不匹配,所需类型是 DataRow"的解决方案
关于值类型与列类型不匹配,所需类型是 DataRow"的解决方案
public static DataTable ConvertDataReaderToDataTable(OleDbDataReader dataReader)
{
//定义DataTable和模式
DataTable datatableTemp = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();
try
{
//动态添加表的数据列
foreach (DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColum = new DataColumn();
//myDataColum.DataType = myRow.GetType();
myDataColum.DataType = System.Type.GetType("System.String");
myDataColum.ColumnName = myRow[0].ToString();
datatableTemp.Columns.Add(myDataColum);
}
//添加表的数据
while (dataReader.Read())
{
DataRow myDataRow = datatableTemp.NewRow();
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
myDataRow[i]= dataReader[i].ToString();
}
datatableTemp.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
dataReader.Close();
return datatableTemp;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}