首页 > 解决方案 > 检查2个datagridview中是否有重复值

问题描述

我正在尝试将行和列与 2 个 datagridview 进行比较。(DGV1) 中的第一列 s1 在 s1 (DGV2) 中找到了重复值。(DGV1) 中的第二列 s2 与 (DGV2) 中的第二列 s2 不匹配。代码有什么问题?

for (int i = 0; i < dataGridView1.RowCount ; i++)
 {
   for (int j = 0; j < dataGridView2.RowCount; j++)
       {
         if ( dataGridView1.Rows[i].Cells[0].Value.ToString() == 
              dataGridView2.Rows[j].Cells[0].Value.ToString())
            { 
               dataGridView1.Rows[i].Cells[0].Style.BackColor = 
               Color.Yellow;
               dataGridView2.Rows[j].Cells[0].Style.BackColor = 
               Color.YellowGreen;
            }
       }     
  }

在此处输入图像描述

标签: c#

解决方案


foreach (DataGridViewRow row1 in table1.Rows) //LOOP ROWS TABLE 1
{
    foreach (DataGridViewCell cell1 in row1.Cells) //LOOP COLUMNS TABLE 1
    {
        foreach (DataGridViewRow row2 in table2.Rows) //LOOP ROWS TABLE 2
        {
            foreach (DataGridViewCell cell2 in row2.Cells) //LOOP COLUMNS TABLE 2
            {
                if (cell1.Value != null && cell2.Value != null&& cell2.Value.ToString() == cell1.Value.ToString())
                {
                    cell1.Style.BackColor = Color.Yellow;
                    cell2.Style.BackColor = Color.YellowGreen;
                }
            }
        }
    }
}

嘿 Marcel16,这应该可以解决您的问题:

在此处输入图像描述


推荐阅读