如何将datagridview1的datagridview单元格与C#中datagridview2的另一个datagridview单元格进行比较

时间:2017-11-02 07:20:24

标签: c# c#-3.0

[if Name(cell data) for datagridview1] == Name(cell data) for datagridview2 background color should be in red color.

2 个答案:

答案 0 :(得分:0)

我认为这应该是您正在寻找的方法。 那可能'是一些语法错误,因为我已经写出了这个错误。但我希望我能帮助你进一步解决这个问题。

不要忘记在datagridview1本身中定义事件。 (在datagridview1>属性>事件下)

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
          string dgv1value = dataGridView1.Rows[e.Rowindex].Cells[e.Columnindex].Value.ToString();
          foreach (DataGridViewRow row in datagridview2.rows)
          {
               if (row.Cells[0].Value.ToString() == dgv1value)
               {
                    //Continue your code here
               }
          }
    }

如果还没有成功,请在评论中告诉我。

答案 1 :(得分:0)

public static void CompareDataGridColumnForward(DataGridView dgv1, DataGridView dgv2)
    {
        try
        {
            for (int i = dgv1.RowCount - 1; i >= 0; i--)
            {
                for (int j = 0; j < dgv2.RowCount - 1; j++)
                {
                    string dgv1value = dgv1.Rows[i].Cells[0].Value.ToString();
                    foreach (DataGridViewRow row in dgv2.Rows)
                    {
                        if (row.Cells[0].Value.ToString() == dgv1value)
                        {
                            row.DefaultCellStyle.BackColor = Color.Red;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
        }
    }

    public static void CompareDataGridColumnReverse(DataGridView dgv1, DataGridView dgv2)
    {
        try
        {
            for (int i = dgv2.RowCount - 1; i >= 0; i--)
            {
                for (int j = 0; j < dgv2.RowCount - 1; j++)
                {
                    string dgv2value = dgv2.Rows[i].Cells[0].Value.ToString();
                    foreach (DataGridViewRow row in dgv1.Rows)
                    {
                        if (row.Cells[0].Value.ToString() == dgv2value)
                        {
                            row.DefaultCellStyle.BackColor = Color.Red;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
        }
    }