Pregunta

private DataRow getDataRowFromReader(IDataReader reader)
{
    DataRow row = new DataRow();
    DataTable tbl = new DataTable();
    for (int i = 0; i < reader.FieldCount; i++)
    {
        Type type = reader[i].GetType();
        if(type.Equals(Type.GetType("DBNull")) || type.Equals(Type.GetType("System.DBNull")))
            type = typeof(string);
        DataColumn col = new DataColumn(reader.GetName(i), type);
        tbl.Columns.Add(col);
    }
    row = tbl.NewRow();
    for (int i = 0; i < reader.FieldCount; i++)
    {
        Type readerType = reader[i].GetType();
        Type rowType = row[i].GetType();
        if (readerType.Equals(rowType))
            row[i] = reader.GetValue(i);
        else
            row[i] = reader.GetString(i);
    }
    return row;
}

Estoy tratando de manejar dbnull en el primer bucle, pero en el segundo tengo todas las filas creadas por newRow () de tipo dbnull.

por ejemplo, RowType ~ dbnull

¿Por qué sucede esto?

¿Fue útil?

Solución

Puede usar esto para averiguar si el valor que está viendo es dbnull:

reader.IsDBNull(i)

ver http://msdn.microsoft.com/en-us/library/system.data.idatarecord.isdbnull.aspx

Para encontrar el tipo de columna en la que se encuentra, intente esto:

reader.GetFieldType(i)

ver http://msdn.microsoft.com/en-us/library/system.data.idatarecord.getfieldtype.aspx

Además, creo que no hay necesidad de new DataRow() en la primera línea, si está abandonando esa referencia haciendo row = tbl.NewRow() Después del primer bucle.

Otros consejos

Usar Convert.IsDBNull(reader[i]).

Comparar el resultado getType () con la cadena es horrible.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top