使用foreach迭代DataTableReader中的行

时间:2014-03-07 22:23:58

标签: c# asp.net sql-server foreach

我可以使用foreach (DataRow row in r)吗?

我有这段代码:

    conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~/App_Data/Database.mdf") + ";Integrated Security=True;User Instance=True";
    string sqlStr = "Select * FROM Msgs WHERE Reciver='"+Reciver+"'";
    SqlDataAdapter daObj = new SqlDataAdapter(sqlStr, conStr);
    DataSet dsObj = new DataSet();
    daObj.Fill(dsObj);
    DataTableReader r = dsObj.Tables[0].CreateDataReader();
    foreach (DataRow row in r)

我运行调试,它停在foreach的行上并给了我这个错误:

Unable to cast object of type 'System.Data.Common.DataRecordInternal' to type 'System.Data.DataRow

我该如何解决?

4 个答案:

答案 0 :(得分:6)

foreach正在尝试从DataRow中投射DataTableReader,而不是DataTableReader

DataTable 读取行,但没有行。它只能逐个读取DataTableReader中的行。 Rafa对这篇文章的回答超过了对DataTableReader的最佳使用。

如果您必须使用while,那么只需将其置于while (r.Read()) { //Access r with r["columnName"] } 循环中:

foreach

如果你想要DataTable,只需遍历foreach (DataRow row in dsObj.Tables[0].Rows) { //Do something with the rows } 本身的行:

foreach

就性能而言,我认为DataTableReader会更好,因为它不需要你实例化另一个对象({{1}}),你也可以获得对行的写访问权限你想修改他们的内容。

答案 1 :(得分:3)

您可以使用以下foreach代替:

while (r.Read())
{
     // r[0], r[1], ... or r["Name"] will give you access to fields
}

请参阅this example from MSDN

答案 2 :(得分:3)

DataTableReader包含DataTable个对象,其形式为一个或多个只读,仅向前结果集。您可以使用DataTableReader.NextResult浏览他们的记录。

上一个链接文档中的示例

using (DataTableReader reader = new DataTableReader(
           new DataTable[] { customerDataTable, productDataTable }))
{
    // Print the contents of each of the result sets. 
    do
    {
        PrintColumns(reader);
    } while (reader.NextResult());
}

答案 3 :(得分:-2)

onStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~/App_Data/Database.mdf") + ";Integrated Security=True;User Instance=True"; string sqlStr = "Select * FROM Msgs WHERE Reciver='"+Reciver+"'"; SqlDataAdapter daObj = new SqlDataAdapter(sqlStr, conStr); DataSet dsObj = new DataSet(); daObj.Fill(dsObj); 
// DataTableReader r = dsObj.Tables[0].CreateDataReader();//



 foreach (DataRow dr in dsObj.Tables[0].rows)
{
enter code here`
/.........
}