user7362545
user7362545

Reputation:

Checking null value for integer from DataBase

I have a student table that references a parent table, as a FK. But a student can be older than 18, in which case he's responsable for himself and the parent_id is set to null. I have to check if the id is null, but:

if (dtreader_resp.Read())
            {
                if(dtreader_resp.GetInt16("resp_id") != null)
                {
                    resp.Resp_id = dtreader_resp.GetInt16("resp_id");
                }
            }

Always returns true. Is there a way to check if that field is null?

Upvotes: 0

Views: 114

Answers (1)

Christian Gollhardt
Christian Gollhardt

Reputation: 17014

You could use IsDBNull or use a nullable int:

var data = sqlReader["resp_id"] as int?;
if (data.HasValue)
{
    var actualValue = data.Value
}

Upvotes: 1

Related Questions