Fix DBNull In C#
Blog Date 13 July 2021
if (dt.Rows["MyValue"] != DBNull.Value)
MyValue = Convert.ToInt32(dt.Rows["MyValue"]);
MyValue = 0
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 firstname.lastname@example.org
David S Squire said :-
I've been struggling with this for some time. It is the '.Value' part I was missing.
22/7//2021 2:55:46 PM UTC
Add a RELEVANT link
Upload an image