C# datagridview单元格值的比较

C# datagridview单元格值的比较,c#,C#,我试图比较两个datagridview单元格的值: if (kk.BoringData.Rows[rows].Cells[0].Value != kk.BoringData.Rows[rows - 1].Cells[0].Value) { ... } 两个单元格值均为“B-1”,但返回true。属性的类型为object,表示测试(两个对象是否在内存中占据相同位置)。要按字符串的值比较字符串,可以尝试使用: 或者在进行如下测试之前将其转换为字符串: if (kk.BoringData.Rows[

我试图比较两个datagridview单元格的值:

if (kk.BoringData.Rows[rows].Cells[0].Value != kk.BoringData.Rows[rows - 1].Cells[0].Value)
{
...
}
两个单元格值均为“B-1”,但返回true。

属性的类型为
object
,表示测试(两个对象是否在内存中占据相同位置)。要按字符串的值比较字符串,可以尝试使用:

或者在进行如下测试之前将其转换为字符串:

if (kk.BoringData.Rows[rows].Cells[0].Value.ToString() != kk.BoringData.Rows[rows - 1].Cells[0].Value.ToString())

尝试将Value属性强制转换为适当的类型,例如string、int、double,然后执行比较


Google for C#unboxing

我在这里要重申一点,因为我有一个类似的问题,找到了上面关于“引用相等”的解释,但添加此代码是为了一个稍微不同的观点

if (e.ColumnIndex == Column1.index && e.RowIndex > 0)
   {
      //if (DataGridView[Column1.Index, e.RowIndex].Value == DataGridView[Column1.Index, e.RowIndex - 1].Value)  //Always false. Reference Equality
      //if ((string)DataGridView[Column1.Index, e.RowIndex].Value == (string)DataGridView[Column1.Index, e.RowIndex - 1].Value) //True or False as expected. Value Equality
      if (DataGridView[Column1.Index, e.RowIndex].Value.Equals(DataGridView[Column1.Index, e.RowIndex - 1].Value)) //True or False as expected. Value Equality
      {//Do Stuff
      }
      else
      {//Do other stuff
      }
   }
if (e.ColumnIndex == Column1.index && e.RowIndex > 0)
   {
      //if (DataGridView[Column1.Index, e.RowIndex].Value == DataGridView[Column1.Index, e.RowIndex - 1].Value)  //Always false. Reference Equality
      //if ((string)DataGridView[Column1.Index, e.RowIndex].Value == (string)DataGridView[Column1.Index, e.RowIndex - 1].Value) //True or False as expected. Value Equality
      if (DataGridView[Column1.Index, e.RowIndex].Value.Equals(DataGridView[Column1.Index, e.RowIndex - 1].Value)) //True or False as expected. Value Equality
      {//Do Stuff
      }
      else
      {//Do other stuff
      }
   }