81

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!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
PipBoy
  • 1,127
  • 4
  • 11
  • 16

12 Answers12

150

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 { .. }.

Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
  • 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? – PipBoy May 03 '12 at 14:40
  • I've edited code - added proper using statements (which close/dispose) connection. You still need to **open** connection – Kamil Lach May 03 '12 at 14:46
  • I think in this instance this will best suit my needs - thanks! – PipBoy May 03 '12 at 15:07
  • 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(); } – user3267567 Jun 28 '22 at 06:21
14

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.

jason
  • 236,483
  • 35
  • 423
  • 525
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

Cade Roux
  • 88,164
  • 40
  • 182
  • 265
5

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.

mgnoonan
  • 7,060
  • 5
  • 24
  • 27
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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

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

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

GoranSu
  • 479
  • 4
  • 9
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 :)

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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
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();
    }
dstineback
  • 103
  • 2
  • 4
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.

Nur.B
  • 319
  • 2
  • 4
0

Just simply check

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

anil soni
  • 75
  • 1
  • 4
-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();
Likurg
  • 2,742
  • 17
  • 22