1

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. enter image description here

1
  • 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 exception Commented Dec 16, 2020 at 2:33

1 Answer 1

4

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())
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.