-5

hi am asking about my error see my screen shot, thanks

DBNULL to other types I create my c# code to read a excel file but something had a problem see above my screen shot

other problem , I inputted your code but will shown an error see screenshot below

Other Error

J.Cloud
  • 11
  • 6

3 Answers3

0

I don't know what database library you're using, but most libraries built on-top of ADO.NET do not always use a .NET null reference to indicate a SQL NULL value. That's what DBNull is for (accessed via DBNull.Value). You can test for SQL NULL by using the Object Reference Equality operator == or Object.ReferenceEquals.

Your code is rather convoluted. I suggest you try this instead:

Object value = row[8]; // I don't know what `row` is, change this to be a more specific type if there are any type-safety constraints on `row[8]`.
if( Object.ReferenceEquals( DBNull.Value, value ) ) {
    // value is SQL NULL
}
else {
    // value is not SQL NULL, but it is not necessarily a Decimal value either

    if( value is Decimal ) {

        return (Decimal)value; // you can't use the shorthand `as` operator with value-types like Decimal
    }
}
Dai
  • 141,631
  • 28
  • 261
  • 374
0

Hope that there may be a chance for row[8] to be DBNull. in such cases you can check that by comparing row[8] with System.DBNull.Value.
try like this:

if (row[8] != System.DBNull.Value))
{
   decimal quantity; 
   if(decimal.TryParse(row[8].ToString(), out quantity)
   {
      item.ONHANDQTY = quantity;
   } 
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
-2

use or (||) condition instead of and (&&) condition, as shown below:

if(onhand == "" || row[8] == System.DBNULL.value)
{
    //your code
}
else
{
    ONHANDQTY=Convert.toDecimal(row[8]);
}
Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
kritikaTalwar
  • 1,730
  • 1
  • 17
  • 25