Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data is Null. This method or property cannot be called on Null values

Tags:

ado.net

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.

like image 439
selvi Avatar asked Sep 22 '11 09:09

selvi


People also ask

What is null data?

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).

What is null property?

If a property's definition does not set the default value of a property, its default value is null.

What are nullable types in C#?

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.


2 Answers

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);
like image 144
Aliostad Avatar answered Sep 19 '22 04:09

Aliostad


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.

like image 34
Marco Avatar answered Sep 22 '22 04:09

Marco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!