Object cannot be cast from DBNull – Solution

I had a DataGridView in my Windows Form Application with an editable column,

This editable column is to get populated with a priority number which I declared as a short in the code.

On the DataGridView.CellValueChanged event, I get the value from the cell, convert it to short, and assign it to a short variable.

short v = Convert.ToInt16(cell.Value);

The problem is whenever I set the cell value to nothing i.e., empty, I get the exception saying

Object cannot be cast from DBNull to other types

What is a DbNull?

Well, according to MSDN DBNull represents a nonexistent value.

In databases, a column of a row might not contain any data i.e., empty, this column will be considered non-existent rather than merely not having a value.

This might be a little bit confusing as the notion of null in and object-oriented programming language is different from the DbNull object, but it is not so. In an object-oriented programming language, null means that there is no reference to an object, while DBNull is an uninitialized variant or nonexistent database column.

Find more about it: DBNull

The solution to the problem is to handle a check that if the value is not null, assign it, otherwise assign the default value.

if (!DBNull.Value.Equals(cell.Value))
{
     short v = Convert.ToInt16(cell.Value);
}
else
{
     short v = 0; // some default value.
}