检查datagrid中的重复行并删除这些行

时间:2014-02-10 09:41:52

标签: c# datagridview

我有比较datagridview1和datagridview2的代码现在我不知道如何删除重复字段。我尝试了dataGridView2.Rows.Remove(row1),但它无法正常工作。

   //pobarvaj
        var style1 = this.dataGridView1.DefaultCellStyle.Clone();
        style1.BackColor = Color.Green;
        var style2 = this.dataGridView2.DefaultCellStyle.Clone();
        style2.BackColor = Color.Blue;
        //primerjaj
        // Create a clone of the DataTable
        // assumes that the DataGridView2 is bound to the duplicates DataTable
        var duplicateTable = (dataGridView2.DataSource as DataTable).Clone();

        // iterating the DataGridView rows to get the right order
        foreach (DataGridViewRow viewRow1 in this.dataGridView1.Rows)
        {
            bool isDuplicate = false;
            DataRowView row1 = viewRow1.DataBoundItem as DataRowView;
            if (row1 != null && viewRow1.DefaultCellStyle != style1)
            {
                foreach (DataGridViewRow viewRow2 in this.dataGridView2.Rows)
                {
                    DataRowView row2 = viewRow2.DataBoundItem as DataRowView;
                    // if row and not already marked, compare the row values (LINQ)
                    if (row2 != null
                        // && viewRow2.DefaultCellStyle != style2
                        && row1.Row["cel1"].Equals(row2.Row["cel2"]))
                    //&& row1.Row.ItemArray.SequenceEqual(row2.Row.ItemArray))
                    {
                        // don't add twice, only necessary if not checked above
                        if (viewRow2.DefaultCellStyle != style2)
                        {
                            // insert values
                            duplicateTable.Rows.Add(row2.Row.ItemArray);
                        }

                        isDuplicate = true;
                        viewRow2.DefaultCellStyle = style2;
                    }
                }
            }
            if (isDuplicate)
            {
                viewRow1.DefaultCellStyle = style1;
                this.dataGridView3.DataSource = duplicateTable;
            }

0 个答案:

没有答案