Input string was not in a correct format - when passing NULL value

465 views Asked by At

I have the following line of code in my web app.

        foreach (DataRow dr in dtDataItemsSets_1.Rows)
        {
            lst_dataItem_1.Add(Convert.ToDecimal(dr["total"].ToString())); ;
        }
        iData.Add(lst_dataItem_1);

If I pass it a decimal it works fine.

However if the value is NULL, I get the following error.

"Input string was not in a correct format"

I understand why this isn't working, but I am not sure how to handle the NULL values?

Any help greatly appreciated.

1

There are 1 answers

0
Sanad On

You can check the value of dr["total"] before converting it to decimal:

foreach (DataRow dr in dtDataItemsSets_1.Rows)
    {
        lst_dataItem_1.Add((dr["total"] is null) ? "NULL" : Convert.ToDecimal(dr["total"].ToString())); ;
    }
    iData.Add(lst_dataItem_1);