Reputation:
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
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
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.
Upvotes: 0