92AlanC
92AlanC

Reputation: 1387

Eliminate repeated rows on DataGridView

I have a DataGridView where the values found in the 1st column should not be repeated, and neither should it have any blank columns. This is the method I've implemented in order to remove this repetition:

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
                }
            }
        }
    }

The result I have is always 2 rows with the same value in the 1st column. Any help will be much appreciated.

Upvotes: 0

Views: 499

Answers (1)

serdar
serdar

Reputation: 1618

After removing a row from the table, the indexes change. Next iteration will not be as expected.

I think it would be better to create a list of objects. Make them unique in terms of your rule. Then set the DataSource property of the datagridview to the object list you have.

Upvotes: 1

Related Questions