Unable to convert System.DBNull

I have a problem when reading data from excel. If cell is empty, I get exception "Unable to cast object of type 'System.DBNull' to type 'System.String'" I've researched stackoverflow and found that DBNullValues can be converted, I tried this suggestion, but my program throws an exception even before it has called method which converts DBValues. Any Suggestions?

            int A = reader.GetOrdinal("A");

            foreach (DbDataRecord record in reader)
            {
                string foo = ConvertFromDBVal<string>(record.GetString(A));
            }
        }
        catch
        {

        }
        conn.Close();
        return AllConnections;
    }

    public static T ConvertFromDBVal<T>(object obj)
    {
        if (obj == null || obj == DBNull.Value)
        {
            return default(T);
        }
        else
        {
            return (T)obj;
        }
    }
Jon Skeet
people
quotationmark

You're calling record.GetString, and I'd expect that to fail, because that's trying to perform the conversion to a string. You should be able to see that in the stack trace. Instead, use record.GetValue:

string foo = ConvertFromDBVal<string>(record.GetValue(A));

Then it won't be performing any conversion before it gets to your method.

people

See more on this question at Stackoverflow