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
}

Jacob Saylor

Software developer in Kentucky

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: