user4376276
user4376276

Reputation:

How to handle SQL Server NULL values

I'm trying to get values from my database, it works when all columns have values. When a value is NULL, it returns an error.

I've managed to find a way to handle with the strings but if there's an integer I don't know how to handle it. I've tried to find a solution but none has worked for me so far! Here's the code, any help would be highly appreciated.

Thanks!

while (dr.Read())
{
    coments comentsar = new coments
            {
                Id = (int)dr["Id"],
                Name = (string)dr["Name"],
                Likes = (int)dr["Likes"],
          //    Signature = dr["Signature"].ToString(),
                Datetime = (DateTime)dr["Datetime"]
            };

    comen.Add(comentsar);

    return comen;
}

Upvotes: 0

Views: 127

Answers (2)

dotnetom
dotnetom

Reputation: 24901

You can check for null value and if the value is not null assign the variable using ternary operator:

Signature  = dr["Signature"] != DBNull.Value ? (string)dr["Signature"] : "No value",
Likes = dr["Likes"] != DBNull.Value ? Convert.ToInt32(dr["Likes"]) : 0,

Upvotes: 1

Ashley Medway
Ashley Medway

Reputation: 7301

You need to change your types to Nullable types.

Change (int)dr["Likes"] to (int?)dr["Likes"]
and Datetime = (DateTime)dr["Datetime"] to Datetime = (DateTime?)dr["Datetime"].

You will also need to update your model coments to allow for nullable types.

Microsoft Nullable Types.

Upvotes: 0

Related Questions