Under normal conditions, a simple test of Object.Equals
(System.DBNull.Value) should be sufficient. But in this case you are
using typed datasets within which each object is strongly typed. It is
my deduction that Objects such as integers might not be nullable and
therefore cannot be compared to DBNull, resulting in the InvalidCast.
It may be helpful to take a hint from Jayg28's suggestion and use
Convert.ToString() on the object first.

Another method may be :

---
// o is an Object returned by your Database
if (o != null && o != DBNull.Value)
{
  // o can be accessed.
}
---

On Jan 31, 7:21 pm, JaffaB <[email protected]> wrote:
> Hi All,
>
> i am trying to use a variable from a DST in a VS2003 project, and I am
> trying to overcome an Invalid Cast Exception of DBnull.  But
> everything I try to test for DBnull, causes the exception as well.
>
> At first, I used a function to check and convert as follows:
>
>                 public static string MNS(object s)
>                 {
>                         if(s==System.DBNull.Value)
>                                 return string.Empty;
>                         else
>                                 return Convert.ToString(s);
>                 }
>
> However, calling this (passing in the column of the table as shown
> below) caused the same casting exception.  Now I have gone specific
> with the test as follows:
>
> DstWastage.AuditRow drAudit = dstWastage.Audit[0];
> if(drAudit.ContainerCode.Equals(System.DBNull.Value) == true) sqlains
> = SqlCEParamAdd(sqlains,""); else sqlains = SqlCEParamAdd
> (sqlains,drAudit.ContainerCode);
>
> the 2nd line, produces the exception error of Invalid Cast Exception :
> StrongTyping_CannotAccessDBNull.
>
> I have also tried..
>
> DstWastage.AuditRow drAudit = dstWastage.Audit[0];
>    if(drAudit.ContainerCode == System.DBNull.Value) sqlains =
> SqlCEParamAdd(sqlains,""); else sqlains = SqlCEParamAdd
> (sqlains,drAudit.ContainerCode);
>
> However, this wont even compile, as it says it cannot compare the
> string (drAudit.ContainerCode) with a type of System.DBNull.Value
>
> Can anybody point me in the right direction for sorting out whether
> the variable is a DBnull or not.

Reply via email to