I want to iterate each cell of my DataGridView and if the value = 0 or 0.00 I want to change it to a - I have the below code, but I am getting an error of
Possible unintended reference comparison
What would be the proper way to achieve what I am after here?
foreach (DataGridViewRow rw in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in rw.Cells)
{
if (rw.Cells[0].Value == "0")
{
rw.Cells[0].Value = "-";
}
}
}
According to the MSDN documentation, DataGridViewCell.Value
returns an object
. Now you'd like to compare this with your string
"0".
When trying to compare object
and string
, you will compare their references, but not their values. Basically you're just checking whether they point to the same object.
If your cell ALWAYS contains objects of type string
, you could simply do the following:
foreach (DataGridViewRow rw in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in rw.Cells)
{
var currentValue = (string)rw.Cells[0].Value;
if (currentValue == "0")
{
currentValue = "-";
}
}
}
A more safe approach:
foreach (DataGridViewRow rw in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in rw.Cells)
{
var currentValue = rw.Cells[0].Value as string;
if (currentValue != null && currentValue == "0")
{
currentValue = "-";
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments