DBNull if statement

PipBoy picture PipBoy · May 3, 2012 · Viewed 166.4k times · Source

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!

Answer

Kamil Lach picture Kamil Lach · May 3, 2012

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();
                 }
              }
           }
        }
     }

this'll automaticly dispose (close) resources outside of block { .. }.