Share via


Convert DBNull to empty string

Question

Thursday, May 28, 2015 3:45 PM

I'm getting data from a DB (FirebirdSQL) that contains in some rows null values for then store in other DB (SQLServer).

I did this validation inside my DTO:

Nombre = row["NOMBRE"] == DBNull.Value ? string.Empty : (string)row["NOMBRE"]

Also before that, I did this validation:

var rfcROW=row["NOMBRE"];
if(rfcROW == DBNull.Value){
     rfcROW=string.Empty;
}

And I get this error: Unable to cast object of type 'System.DBNull' to type 'System.String'

How can I convert a DBNull to empty string? I'll appreciate any help.

All replies (1)

Thursday, May 28, 2015 4:08 PM âś…Answered

ArCiGo

if(rfcROW == DBNull.Value){
     rfcROW=string.Empty;
}

And I get this error: Unable to cast object of type 'System.DBNull' to type 'System.String'

How can I convert a DBNull to empty string? I'll appreciate any help.

Try using  conditional operator (?:)  instead of if condition check like given below

You can try with the below code

var rfcROW = (row["NOMBRE"] == DBNull.Value) ? string.Empty : row["NOMBRE"].ToString();