比较datagridview1和datagridview2并标记相同的值c# [英] Compare datagridview1 and datagridview2 and mark same values c#

查看:270
本文介绍了比较datagridview1和datagridview2并标记相同的值c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在比较datagridviews时遇到问题。我需要比较2个datagridviews,如果值相同,请标记它们或执行某些操作。 (我从excel导入值)

I have a problem with comparing datagridviews. I need to compare 2 datagridviews and if values are same, mark them or do something. (I import values from excel)

我不能使用linq太慢了。

I cant use linq it's slow.

我尝试了一下,但似乎我无法使其正常工作:

I try this but it seems I cant get it to work:

for (int currentRow = 0; currentRow < grv.Rows.Count; currentRow++)
{
   var rowToCompare = grv.Rows[currentRow]; // Get row to compare against other rows

   // Iterate through all rows 
   //
   foreach (var row in grv.Rows)
   {  
       if (rowToCompare.equals(row) continue; // If row is the same row being compared, skip.

       bool duplicateRow = true;

       // Compare the value of all cells
       //
       for (int cellIndex; cellIndex < row.Cells.Count; cellIndex++)
       {
          if (!rowToCompare.Cells[cellIndex].Value.equals(row.Cells[cellIndex].Value))
          {
             duplicateRow = false;
             break;
          }
       }

       if (duplicateRow)
       {
           grv.Rows.Remove(row);
       }
   }
}


推荐答案

private void button5_Click(object sender, EventArgs e)
    {
        DataTable src1 = dataGridView1.DataSource as DataTable;
        DataTable src2 = dataGridView2.DataSource as DataTable;
        for (int i = 0; i < src1.Rows.Count; i++)
        {
            var row1 = src1.Rows[i].ItemArray;
            var row2 = src2.Rows[i].ItemArray;

            for (int j = 0; j < row1.Length; j++)
            {
                if (!row1[j].ToString().Equals(row2[j].ToString()))
                {
                    dataGridView1.Rows[i].Cells[j].Style.BackColor = Color.Red;
                    dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Red;
                }
            }
        }

这将突出显示哪些单元格具有相同的值。如果两个datagridviews的行数应该相同。

This will highlight the cells which have the same values. Provided both the datagridviews should have same number of rows.

这篇关于比较datagridview1和datagridview2并标记相同的值c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆