reading a empty cell, gives object reference error

倖福魔咒の 提交于 2019-12-05 21:05:28

问题


When I read a cell by doing Worksheets.Cells[2,5].value.ToString();

I get a error "System.NullReferenceException: Object reference not set to an instance of an object."

What would be a good way to check for null and then assign the value, without having to have a "if" statement.


回答1:


 string strValue = Worksheets.Cells[2,5].value==null ? string.Empty : Worksheets.Cells[2,5].value.ToString();

or

object objValue = Worksheets.Cells[2,5].value ?? string.Empty


来源:https://stackoverflow.com/questions/11964271/reading-a-empty-cell-gives-object-reference-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!