DBNull if statement
Asked Answered
P

13

82

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!

Powys answered 3/5, 2012 at 12:55 Comment(2)
if you are expecting one cell, consider ExecuteScalarColumniation
I came here because == null did not work. Amazed that different types of NULL exist, and that DBNull even has a value...Omnipotent
N
156

This should work.

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

also need to add using statement, like bellow:

using (var objConn = new SqlConnection(strConnection))
     {
        objConn.Open();
        using (var objCmd = new SqlCommand(strSQL, objConn))
        {
           using (var rsData = objCmd.ExecuteReader())
           {
              while (rsData.Read())
              {
                 if (rsData["usr.ursrdaystime"] != System.DBNull.Value)
                 {
                    strLevel = rsData["usr.ursrdaystime"].ToString();
                 }
              }
           }
        }
     }

that'll automatically dispose (close) resources outside of block { .. }.

Nicolella answered 3/5, 2012 at 12:57 Comment(4)
Does the using statement replace my initial connection strings? I'm assuming it would replace the following objConn = new SqlConnection(strConnection); objConn.Open(); Would I still use the objCmd& rsdata strings?Powys
I've edited code - added proper using statements (which close/dispose) connection. You still need to open connectionNicolella
I think in this instance this will best suit my needs - thanks!Powys
remember to remove the extra ) when you are trying this code out. i tried to edit the post but the "suggested edit queue is full" if (rsData["usr.ursrdaystime"] != System.DBNull.Value) { strLevel = rsData["usr.ursrdaystime"].ToString(); }Thyself
S
15

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.

Smite answered 3/5, 2012 at 12:58 Comment(0)
W
8

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

Wigwam answered 3/5, 2012 at 13:3 Comment(0)
G
6

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.

Gallinacean answered 3/5, 2012 at 12:58 Comment(1)
That will take him in if condition. Make == to !=Edgewise
C
2

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

Columniation answered 3/5, 2012 at 12:58 Comment(0)
T
1

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

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

Thermography answered 24/10, 2018 at 12:48 Comment(0)
D
1

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

Dumanian answered 8/6, 2022 at 0:34 Comment(0)
S
0
if(!rsData.IsDBNull(rsData.GetOrdinal("usr.ursrdaystime")))
{
  strLevel = rsData.GetString("usr.ursrdaystime"); 
}

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull.aspx

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx

Sparky answered 3/5, 2012 at 13:1 Comment(0)
C
0

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();
    }
Contradistinction answered 8/11, 2017 at 18:22 Comment(0)
N
0

There is still such an alternative option:

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

You need to know exactly which column counts.

Nady answered 20/9, 2021 at 17:39 Comment(0)
F
0

Just simply check

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

Frere answered 1/3, 2022 at 9:44 Comment(0)
H
-1

There is no need for System prefix since almost every class has that library.

if (reader["ColumnName"] != DBNull.Value)
{
    do someting;
}
Henandchickens answered 26/1 at 23:37 Comment(0)
I
-2

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();
Infantine answered 3/5, 2012 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.