Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a datatable I have a string column 'shipping charges'. In one of the datatable row, this column is empty. I want to pass the values from this column to an int variable 'v_shippingcharges'. I tried with the following code but get error at line 'v_shippingcharges=...' I get the error as: 'Object cannot be cast from DBNull to other types'.


C#
if (dtCurrentTable.Rows[i]["Shipping Charges"] != null)
                   {
                       v_shippingcharges = Convert.ToInt32(dtCurrentTable.Rows[i]["Shipping Charges"]);
                   }
                   else
                   {
                       v_shippingcharges = 0;
                   }
Posted

1 solution

According to the error the column isn't empty it's NULL - it's not the same...
Your problem is that you try to convert NULL to int which is not nullable type...
You have a few options
1. In SQL do ISNULL(column, 0) - or any other default value
2. In the code do if(Convert.IsDBNull(column)){initialize with some default value} - http://msdn.microsoft.com/en-us/library/system.convert.isdbnull.aspx[^]
3. You may use nullable int in your code - http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx[^]
 
Share this answer
 
v2
Comments
S.Rajendran from Coimbatore 27-Mar-14 7:11am    
If it is null I want to assign v_shhipingcharges=0. This is not happenning. It is not that I want to convert null to int.
Kornfeld Eliyahu Peter 27-Mar-14 7:14am    
That because null is not DBNull - you have to use Convert.IsDBNull...
S.Rajendran from Coimbatore 27-Mar-14 7:23am    
Is DBNull for dataset or datatable?
Kornfeld Eliyahu Peter 27-Mar-14 7:27am    
DBNull is a class (type) - http://msdn.microsoft.com/en-us/library/system.dbnull(v=vs.110).aspx
It used in all the System.Data namespace and other places...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900