I use the String.IsNullorEmpty to check if a cell in Excel worksheet is null or empty. Why VS2019 still reports a error if the cell is empty?
I am sure the worksheet wshIO exists and the intRowIO is 1 when this error came out. The code associated with this worksheet before this line works very well.

-
Note, don't paste images of code or errors. They re hard to read, and cannot be searched by a search engines and indexed. Instead paste that actual code, and the actual exceptionTheGeneral– TheGeneral2020-12-16 02:33:27 +00:00Commented Dec 16, 2020 at 2:33
Add a comment
|
1 Answer
You are calling ToString on (potentially) a null dynamic type.
For instance, it's the same scenario as the following:
dynamic s = null;
s.ToString(); // Cannot perform runtime binding on a null reference
One fix is to use the null conditional operator, which will check the dynamic type for null.
string.IsNullOrEmpty(s?.ToString());
Or related to your example:
string.IsNullOrEmpty(something.Cells[x,y].Value2?.ToString())
2 Comments
Peter Lau
Thank you, General. You are right. Actually I just need to check if the range is null. I don't need to get the string from the range, which might be Null. I used something.Cells[x,y]!=Null solved the issue.
Peter Lau
Eventually, I use string.IsNullOrEmpty(something.Cells[x,y].Text) in my code as Cells[x,y]!=Null does not work actually. !=Null cannot detect a blank cell. I don't know why. I guess that's a separated question.