2012-02-01 146 views

回答

30

我知道這是舊的,但這裏的答案似乎已經錯過了有機磷農藥的問題點。

DataTables有一個名爲CreateDataReader的方法,它將允許您將DataTable轉換爲DbDataReader對象。在這種情況下,一個DataTableReader

DataTable table = new DataTable(); 
//Fill table with data 
//table = YourGetDataMethod(); 
DataTableReader reader = table.CreateDataReader(); 

我應該指出,這不會提高性能,因爲您應該使用其中一種。

這裏有一些更多的資源對此事:

2

例如

public DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader) 
{ 
DataTable datatable = new DataTable(); 
DataTable schemaTable = dataReader.GetSchemaTable(); 

try 
{ 

foreach(DataRow myRow in schemaTable.Rows) 
{ 
DataColumn myDataColumn = new DataColumn(); 
myDataColumn.DataType = myRow.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].ToString(); 
} 
datatable.Rows.Add(myDataRow); 
myDataRow = null; 
} 
schemaTable = null; 
return datatable; 
} 
catch(Exception ex) 
{ 
Error.Log(ex.ToString()); 
return datatable; 
} 

} 
+0

我想將datatable轉換爲datareader。 – user1049021 2012-02-01 06:29:07

0
public DataTable GetTable(IDataReader _reader) 
{ 
DataTable dataTable1 = _reader.GetSchemaTable(); 
DataTable dataTable2 = new DataTable(); 
string[] arrayList = new string[dataTable1.Rows.Count]; 
for (int i = 0; i < dataTable1.Rows.Count; i++) 
{ 
DataColumn dataColumn = new DataColumn(); 
if (!dataTable2.Columns.Contains(dataTable1.Rows[i][ "ColumnName "].ToString())) 
{ 
dataColumn.ColumnName = dataTable1.Rows[i][ "ColumnName "].ToString(); 
dataColumn.Unique = Convert.ToBoolean(dataTable1.Rows[i][ "IsUnique "]); 
dataColumn.AllowDBNull = Convert.ToBoolean(dataTable1.Rows[i][ "AllowDBNull "]); 
dataColumn.ReadOnly = Convert.ToBoolean(dataTable1.Rows[i][ "IsReadOnly "]); 
dataColumn.DataType = (Type)dataTable1.Rows[i][ "DataType "]; 
arrayList[i] =dataColumn.ColumnName; 
dataTable2.Columns.Add(dataColumn); 
} 
} 
dataTable2.BeginLoadData(); 
while (_reader.Read()) 
{ 
DataRow dataRow = dataTable2.NewRow(); 
for (int j = 0; j < arrayList.Length ; j++) 
{ 
dataRow[arrayList[j]] = _reader[arrayList[j]]; 
} 
dataTable2.Rows.Add(dataRow); 
} 
_reader.Close(); 
dataTable2.EndLoadData(); 
return dataTable2; 
} 
+0

僅供參考,DataTable.Loan(DataReader)可以做到這一點以及更多。特別是,當讀者使用KeyInfo創建時。 – AMissico 2013-04-11 18:09:41

0

使用DataTable的構造函數,

DataTable table = new DataTable(); 
//Fill table with data 
DataTableReader reader = new DataTableReader(table); 

好好看看!