Data is Null. This method or property cannot be called on Null values
My solution was to create an extension method:
static class DataReaderExtensions
{
public static string GetStringNullCheck(this IDataReader reader, int ordinal)
{
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
}
So I can use it as:
StrBcc = rd.GetStringNullCheck(2);
You should use
if (!rd.IsDBNull(2))
StrBcc = rd.GetString(2);
That's because when you use string.IsNullOrEmpty(x)
you are telling your app that x
is a string, while is a database null
value, which is different from a string whose value is null.
If your values can be NULL then using SqlTypes instead can be a safer solution as they all implement INullable:
StrBcc = rd.GetSqlString(2);
or if you like extension methods:
public static class DataReaderExtensions
{
public static T GetValueOrNull<T>(this SqlDataReader reader, int ordinal) where T : class
{
return !reader.IsDBNull(ordinal) ? reader.GetFieldValue<T>(ordinal) : null;
}
public static T? GetValueOrNullable<T>(this SqlDataReader reader, int ordinal) where T : struct
{
if (reader.IsDBNull(ordinal)) return null;
return reader.GetFieldValue<T>(ordinal);
}
}