CurlyFro
CurlyFro

Reputation: 1882

How do I get the value of a cell by row index and column index

currently i'm doing this:

string cellValue = sheet.get_Range("A12", _missing).Value2.ToString();

this works but i really need to select a cell by row and column index.

i get a null exception when i try

string cellValue = ((Range)sheet.Cells[row, column]).Value2.ToString();

any ideas?

Upvotes: 7

Views: 24173

Answers (2)

Joe Johnston
Joe Johnston

Reputation: 2936

I had the same issue. The nullref would happen when the cell I was reading was empty.

string foo = (((Range) ActiveWorksheet.Cells[row, column]).Value2 != null
            ? ((Range) ActiveWorksheet.Cells[row, column]).Value2.ToString()
            : "Coalesce some false string here..."); 

Notice that you have to check for null before you attempt to transform or cast the value.

Upvotes: 0

Zach Johnson
Zach Johnson

Reputation: 24232

Where does the ArgumentNullException occur? Try separating out your code like this and step through it:

object rangeObject = sheet.Cells[row, column];
Range range = (Range)rangeObject;
object rangeValue = range.Value2;
string cellValue = rangeValue.ToString();

This will show you where the null object is.

Upvotes: 8

Related Questions