if (!string.IsNullOrEmpty(rd.GetString(2)))
{
StrBcc = rd.GetString(2);
}
Error: System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
A null value in a relational database is used when the value in a column is unknown or missing. A null is neither an empty string (for character or datetime data types) nor a zero value (for numeric data types).
If a property's definition does not set the default value of a property, its default value is null.
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values. For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With