Resolve the Error Object cannot be cast from DBNull to other Types

Reason for the error

In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source: MSDN.

Actual Code which I faced error

Before changed the code,

  1. if (ds.Tables[0].Rows[0][0] == null// Which is not working  
  2. {  
  3.     seqno = 1;  
  4. }  
  5. else  
  6. {  
  7.     seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;  
  8. }  
After changed the code,
  1. if (ds.Tables[0].Rows[0][0] == DBNull.Value) //which is working properly  
  2. {  
  3.     seqno = 1;  
  4. }  
  5. else  
  6. {  
  7.     seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;  
  8. }  
Conclusion

When the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.