'DBNull if statement

I'm trying to execute a stored procedure and then use an if statement to check for null values and I'm coming up short. I'm a VB guy so please bear with me if I'm making a schoolboy syntax error.

objConn = new SqlConnection(strConnection);
objConn.Open();
objCmd = new SqlCommand(strSQL, objConn);
rsData = objCmd.ExecuteReader();
rsData.Read();

if (!(rsData["usr.ursrdaystime"].Equals(System.DBNull.Value)))
        {
            strLevel = rsData["usr.ursrdaystime"].ToString();

        }

Would this allow me to check whether the SQL connection is returning just a value and if so then populating my string?

I'm used to being able to just check the below to see if a value is being returned and not sure I'm doing it correctly with C#

If Not IsDBNull(rsData("usr.ursrdaystime"))

Any help would be appreciated!



Solution 1:[1]

The idiomatic way is to say:

if(rsData["usr.ursrdaystime"] != DBNull.Value) {
    strLevel = rsData["usr.ursrdaystime"].ToString();
}

This:

rsData = objCmd.ExecuteReader();
rsData.Read();

Makes it look like you're reading exactly one value. Use IDbCommand.ExecuteScalar instead.

Solution 2:[2]

The closest equivalent to your VB would be (see this):

Convert.IsDBNull()

But there are a number of ways to do this, and most are linked from here

Solution 3:[3]

Yes, just a syntax problem. Try this instead:

if (reader["usr.ursrdaystime"] != DBNull.Value)

.Equals() is checking to see if two Object instances are the same.

Solution 4:[4]

Consider:

if(rsData.Read()) {
  int index = rsData.GetOrdinal("columnName"); // I expect, just "ursrdaystime"
  if(rsData.IsDBNull(index)) {
     // is a null
  } else {
     // access the value via any of the rsData.Get*(index) methods
  }
} else {
  // no row returned
}

Also: you need more using ;p

Solution 5:[5]

Solution 6:[6]

I use String.IsNullorEmpty often. It will work her because when DBNull is set to .ToString it returns empty.

if(!(String.IsNullorEmpty(rsData["usr.ursrdaystime"].toString())){
        strLevel = rsData["usr.ursrdaystime"].toString();
    }

Solution 7:[7]

Ternary operator should do nicely here: condition ? first_expression : second_expression;

strLevel = !Convert.IsDBNull(rsData["usr.ursrdaystime"]) ? Convert.ToString(rsData["usr.ursrdaystime"]) : null

Solution 8:[8]

There is still such an alternative option:

strLevel = rsData.GetValue(0) is DBNull? "" : rsData.GetString(0);

You need to know exactly which column counts.

Solution 9:[9]

Just simply check

string val= string.IsNullOrEmpty(rsData["usr.ursrdaystime"]?"":rsData["usr.ursrdaystime"].ToString())

Solution 10:[10]

I know this is a 10+ year old question, but I happened across this and was recently debugging a casting SQL null issue in a .Net 6 app using "Microsoft.Data.SqlClient" Version="5.0.0-preview2.22096.2", using the DataTableReader

You'll want to use the reader's built-in IsDBNull method to test a value before retrieving it, because the implicit (or explicit) cast from using any of the Get* functions may throw an exception (varies on type)

So for a line-if solution, the following is BAD: DateTime lastSentDate = DBNull.Value.Equals(reader.GetDateTime("LastSentDT")) ? reader.GetDateTime("LastSentDT") //Null can't convert to DateTime, exception thrown

This is good: DateTime lastSentDate = !reader.IsDBNull("LastSentDT") ? reader.GetDateTime("LastSentDT") : DateTime.Parse("1-1-2022");

Hope this helps in 2022 :)

Solution 11:[11]

At first use ExecuteScalar

 objConn = new SqlConnection(strConnection);
 objConn.Open();
 objCmd = new SqlCommand(strSQL, objConn);
 object result = cmd.ExecuteScalar();
 if(result == null)
     strLevel = "";
 else 
     strLevel = result.ToString();