简体   繁体   中英

Transformation: Unable to cast object of type 'System.DBNull' to type 'System.String'

I've seen questions similar to mine but my approach is slightly different and I am not familiar enough with C# to put it together. I am using the following code in an ASPX transformation:

  <%# !string.IsNullOrEmpty((string)Eval("XYZ")) ? "<tr>XYZ</tr>" : "" %>

The error comes up when the field is null because it cannot be converted to a string. How do I re-write this to check for a null value without converting to a string before the actual check? There might be a limitation in the CMS that I'm using which would explain why the previous dev did not use another approach, but I will test your suggestions.

Use

<%# !string.IsNullOrEmpty(Convert.ToString(Eval("XYZ"))) ? "<tr>XYZ</tr>" : "" %>

DBNull is a special value when reading from the database that tells you that you have read from an empty value in the database. The Convert class does already deal with DBNull values correctly. Convert.ToString(DBNull value) will return an empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM