Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert null field to zero before converting to int?

Tags:

c#

ado.net

In my program, I'm looping through a datatable to get data from each field. One line of my code looks like this:

int LYSMKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"]);

Basically, I'm just taking the value that's in the cell and converting it to an int32. I run into a problem, though, when the data in the field is a null. I get an Invalid Cast error message about not being able to convert a "DBNull" to another type.

So, I know that I can just check the value of the field before I try to convert it by doing something like this:

if (resultsDT.Rows[currentRow]["LYSMKWh"] == null)
            {
                resultsDT.Rows[currentRow]["LYSMKWh"] = 0;
            }

But, is there a better way to do this? Is there something I can do "inline" while I'm trying to convert the value without having to resort to using the if ?

EDIT: I did try using this suggested method:

int LYSMKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"] ?? "0");

Unfortunately, I still received the Invalid Cast error message with regards to the DBNull type. It was suggested that I could have problems using the ?? operator if the types on either side were different.

Also, since I have complete control over the data that I'm building my datatable with, I changed it so that no null values would be written to any field. So, that pretty much negates the need to convert a null to an int32, in this case. Thanks for all the advice, everyone!

like image 976
Kevin Avatar asked Aug 17 '11 16:08

Kevin


People also ask

Which function can we use to convert null values to zero?

Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0.

What happens if you cast null to int?

In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.

Does convert ToInt32 handle null?

ToInt32(string s) method converts the string to integer. If string s is null , then it will return 0 rather than throw ArgumentNullException . If string s is other than integer value, then it will throw FormatException .


2 Answers

You could do this:

var LYSMKWh =
    resultsDT.Rows[currentRow]["LYSMKWh"].Equals(DBNull.Value)
    ? 0
    : Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"]);
like image 112
Yuck Avatar answered Oct 12 '22 01:10

Yuck


use the ?? operator:

resultsDT.Rows[currentRow][...] ?? "0"

(expecting the field to be a string - if not change the "0")

like image 35
Random Dev Avatar answered Oct 12 '22 00:10

Random Dev