StealthRT
StealthRT

Reputation: 10552

Seeing if comment in cell is null using Excel interlop c#.net

Hey all I am using the code below in order to find out if a cell in the Excel sheet that I am parsing thru has a comment or not.

int columnCount = ws.UsedRange.Columns.Count;
Dictionary<string,bool> storedValidaters = new Dictionary<string, bool>();

for (int c = 1; c < columnCount; c++)
{
   if (ws.Cells[2, c].Comment.Shape.AlternativeText != null)
   {
      string columnName = ws.Cells[2, c].Value2.ToString();
      string myComment = ws.Cells[2, c].Comment.Shape.AlternativeText.ToString().Replace("Text Box: ", "");

      storedValidaters.Add(columnName, true);
   } else {
      //the value is null so its false
      string columnName = ws.Cells[2, c].Value2.ToString();

      storedValidaters.Add(columnName, false);
   }
}

It loops a few times but once it gets to a cell that does not have a comment, it poops.

enter image description here

Having the error of Cannot perform runtime binding on a null reference.

I did a few searches to find out if anyone else had working code in order to check for null but have been unable to find a working example.

Anyone know of a way to do this?

Upvotes: 0

Views: 64

Answers (1)

mjwills
mjwills

Reputation: 23983

I would recommend changing:

Comment.Shape.AlternativeText

to:

Comment?.Shape?.AlternativeText

The null conditional operator will ensure that the code will continue to work as expected regardless of whether the Comment is null, or the Shape is null or the AlternativeText is null.

Upvotes: 1

Related Questions