How to get a DataRow out the current row of a DataReader?

后端 未结 2 883
走了就别回头了
走了就别回头了 2021-02-18 13:12

Ok, I would like to extract a DataRow out a DataReader. I have been looking around for quite some time and it doesn\'t look like there is a simple way

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-18 13:29

    Is there any way to extract a DataRow out the current row of a DataReader ?

    No, at least no simple way. Every DataRow belongs to one Table. You cannot leave that property empty, you cannot even change the table(without using ImportRow).

    But if you need DataRows, why don't you fill a DataTable in the first place?

    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)
    

    If you really need to get the row(s) from the DataReader you can use reader.GetSchemaTable to get all informations about the columns:

    if (reader.HasRows)
    {
        DataTable schemaTable = reader.GetSchemaTable();
        DataTable data = new DataTable();
        foreach (DataRow row in schemaTable.Rows)
        {
            string colName = row.Field("ColumnName");
            Type t = row.Field("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];
            }
        }
    }
    

    But that is not really efficient.

提交回复
热议问题