Question

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;
}

I'm trying to handle DBNull in the 1st loop, but in the second I have then all rows created by NewRow() of DBNull type.

e.g. rowType ~ DBNull

Why this is happen?

Was it helpful?

Solution

You can use this to find out if the value you're looking at is DBNull:

reader.IsDBNull(i)

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

To find the type of the column you're on, try this:

reader.GetFieldType(i)

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

Also, I think there's no need for new DataRow() on the first line, if you are abandoning that reference by doing row = tbl.NewRow() after the first loop.

OTHER TIPS

Use Convert.IsDBNull(reader[i]).

Comparing GetType() result with string is awful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top