Object Cannot Be Cast From DBNull To Other Types : Resolved

A quick post for you guys. I’m currently debugging a windows form application and came across “Object Cannot Be Cast From DBNull To Other Types”. Basically what this translates to is that you have to check for the DBNull before converting. For example :

 

PrimaryKeyInt = Convert.ToInt32(datagridrow["SomeRowId"]);

You would just need to add

if(datagridrow["SomeRowId"] != DBNull.Value)
{
     PrimaryKeyInt = Convert.ToInt32(datagridrow["SomeRowId"]);
}
else
{
    //Whatever you want to set the PrimaryKeyInt to if that fails
}

Releated Post

Leave a Reply

%d bloggers like this: