消除 DataGridView 上的重复行
Eliminate repeated rows on DataGridView
我有一个 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
}
}
}
}
我得到的结果总是第 1 列中具有相同值的 2 行。
任何帮助将不胜感激。
从 table 中删除一行后,索引发生变化。下一次迭代将不会像预期的那样。
我认为创建一个对象列表会更好。根据您的规则使它们独一无二。然后将datagridview的DataSource属性设置为你拥有的对象列表。
我有一个 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
}
}
}
}
我得到的结果总是第 1 列中具有相同值的 2 行。 任何帮助将不胜感激。
从 table 中删除一行后,索引发生变化。下一次迭代将不会像预期的那样。
我认为创建一个对象列表会更好。根据您的规则使它们独一无二。然后将datagridview的DataSource属性设置为你拥有的对象列表。