Reputation: 189
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?
Upvotes: 1
Views: 2825
Reputation: 887415
The Value
property is of type Object
.
Therefore, you're using the standard ==
operator, which compares objects by reference.
To compare strings correctly, you need to compare them by value. (Because you can have two different String
instances holding the same value)
Change it to
if ((string)MISCdataGridView1.Rows[i].Cells[2].Value == "Something")
Upvotes: 0
Reputation: 59645
The DataGridViewCell.Value
property is of type Object
and therefore you have to cast to String
(String)dataGridview.Rows[i].Cells[j].Value == "Something"
or rely on Object.Equals()
.
Object.Equals(dataGridview.Rows[i].Cells[j].Value, "Something")
Using Object.Equals()
is more robust because it can deal with the value not being of type String
. On the other hand using the cast emphasizes the fact that the value must be a String
and will throw an exception if it is not - clearly showing that you probably have a bug.
Upvotes: 2
Reputation: 124642
It looks like "Value" returns an object, and you are comparing against a string, so it is comparing references, when you probably want to compare the value, i.e., "Something". Cast the left side to a string (or call ToString(), whatever, just make sure that you are explicitly comparing two strings).
Upvotes: 0