This is something I thought would be easier than it’s turning out to be. For whatever reason, I can’t seem to figure out a way to make what I’m trying to do here work with an If statement:
List<int> miscTimes = new List<int>();
for (int i = 0; i < MISCdataGridView1.RowCount; i++)
{
if (MISCdataGridView1.Rows[i].Cells[2].Value == "Something")
{
miscTimes.Add(Convert.ToInt32(MISCdataGridView1.Rows[i].Cells[3].Value));
}
}
return miscTimes;
For some reason, I can’t get it to like anything I do with the if statement:
if (MISCdataGridView1.Rows[i].Cells[2].Value == "Something")
it doesn’t throw an exception, but it’s not building my list. It has the green underline and says “Possible unintended reference comparison; cast the left side type to ‘string'”
I’ve tried converting to string and all of that. How should I go about this?
The
DataGridViewCell.Valueproperty is of typeObjectand therefore you have to cast toStringor rely on
Object.Equals().Using
Object.Equals()is more robust because it can deal with the value not being of typeString. On the other hand using the cast emphasizes the fact that the value must be aStringand will throw an exception if it is not – clearly showing that you probably have a bug.