要將OleDbDataReader查詢結果轉換為DataTable,可以按照以下步驟進行操作:
DataTable dataTable = new DataTable();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
DataColumn column = new DataColumn();
column.ColumnName = row["ColumnName"].ToString();
column.DataType = (Type)row["DataType"];
dataTable.Columns.Add(column);
}
while (reader.Read())
{
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < reader.FieldCount; i++)
{
dataRow[i] = reader.GetValue(i);
}
dataTable.Rows.Add(dataRow);
}
完整示例代碼如下:
DataTable dataTable = new DataTable();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
DataColumn column = new DataColumn();
column.ColumnName = row["ColumnName"].ToString();
column.DataType = (Type)row["DataType"];
dataTable.Columns.Add(column);
}
while (reader.Read())
{
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < reader.FieldCount; i++)
{
dataRow[i] = reader.GetValue(i);
}
dataTable.Rows.Add(dataRow);
}
這樣,OleDbDataReader查詢結果就會轉換為DataTable對象。