消除DataGridView上的重复行

时间:2015-11-09 12:28:23

标签: c# datagridview repeat

我有一个DataGridView,其中第一列中找到的值不应重复,也不应该有任何空白列。这是我为了消除这种重复而实施的方法:

public static void eliminateRepetition(DataGridView table)
    {
        for (int currentRow = 0; currentRow < table.RowCount; currentRow++)
        {
            DataGridViewRow rowToCompare = table.Rows[currentRow];
            foreach (DataGridViewRow row in table.Rows)
            {
                if (row.Equals(rowToCompare)) // If the row to compare is the current row, skip
                {
                    continue;
                }
                if (row.Cells[0].Value != null && rowToCompare.Cells[0].Value != null)
                {
                    if (int.Parse(row.Cells[0].Value.ToString()) != int.Parse(rowToCompare.Cells[0].Value.ToString())) // 1st column values must match in order to be considered as a repetition
                    {
                        continue;
                    }
                    else
                    {
                        table.Rows.Remove(row); // Remove repeated row
                    }
                }
                else
                {
                    table.Rows.Remove(row); // Remove blank rows
                }
            }
        }
    }

我的结果总是2行,第1列中的值相同。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

从表中删除一行后,索引会发生变化。下一次迭代不会像预期的那样。

我认为创建一个对象列表会更好。根据您的规则使它们独一无二。然后将datagridview的DataSource属性设置为您拥有的对象列表。