c# – 如何獲取DataRow的DataReader的當前行?
好的,我想提取一個DataRow的DataReader.我一直在尋找相當一段時間,看起來並不像有一個簡單的方法來做到這一點.
我瞭解一個DataReader是更多的行的集合,但它只讀一行當時.
所以我的問題是:有沒有辦法從DataRead中提取DataRow的當前行?
Is there any way to extract a DataRow out the current row of aDataReader ?
不,至少沒有簡單的方法.每個DataRow屬於一個ofollow,noindex" target="_blank">Table .您不能將該屬性留空,甚至不能更改表(不使用ImportRow).
但是如果您需要DataRows,為什麼首先填寫DataTable?
DataTable table = new DataTable(); using(var con = new SqlConnection("....")) using(var da = new SqlDataAdapter("SELECT ... WHERE...", con)) da.Fill(table); // now you have the row(s)
如果您真的需要從DataReader獲取行,您可以使用
reader.GetSchemaTable
獲取有關列的所有信息:
if (reader.HasRows) { DataTable schemaTable = reader.GetSchemaTable(); DataTable data = new DataTable(); foreach (DataRow row in schemaTable.Rows) { string colName = row.Field<string>("ColumnName"); Type t = row.Field<Type>("DataType"); data.Columns.Add(colName, t); } while (reader.Read()) { var newRow = data.Rows.Add(); foreach (DataColumn col in data.Columns) { newRow[col.ColumnName] = reader[col.ColumnName]; } } }
但這不是真的有效率.
http://stackoverflow.com/questions/18511700/how-to-get-a-datarow-out-the-current-row-of-a-datareader