Home

Fix DBNull In C#

Blog Date 13 July 2021

The Code

        if (dt.Rows[0]["MyValue"] != DBNull.Value)
        {
            MyValue = Convert.ToInt32(dt.Rows[0]["MyValue"]);
        }
        else
        {
            MyValue = 0
        }

The Explanation

Blasted nulls! If an SQL query returns nothing then of course C# doesn't know how to convert nothing to a string or an integer or whatever. So you need an "if" to catch any empty SQL responses. Or perhaps just one column is empty (null) in the database.

DBNull.Value seems an odd choice. Remember though this is not just null as in not existing. Nor is it an empty string. I get the feeling a database returning a null is not quite the same as a regular null or nothing. So DBNull.Value is a "thing" that means "nothing from a DataBase".

Anyhoo, DBNull.Value can be matched and handled appropriately.


Need a C# coder? Contact ren@techsolus.co.uk

Reader's Comments

David S Squire said :-
I've been struggling with this for some time. It is the '.Value' part I was missing.
07/22//2021 14:55:46 UTC

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog