简体   繁体   中英

comparison of datagridview cell values

I am trying to compare values of two datagridview cells:

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

Both cell values are "B-1", but it returns true.

The Value property is of type object , meaning the != operator tests for reference equality (whether the two objects occupy the same location in memory). To compare the strings by their values you can try using Equals :

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

Or convert them to strings before testing them like this:

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

Try casting the Value property to the apropriate type eg string, int, double and then perform the comparison.

Google for C# unboxing

I'm going to reiterate a bit here as I had a similar problem and found the explanation above regarding 'Reference Equality', but adding this code for a slightly different viewpoint.

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
      }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM