Reputation: 134
I am trying to compare the rows of a Datagridview and that it removes the rows that are repeated. I think that I´m doing something wrong. Here´s the code:
public void Compare(DataGridView grv)
{
grv.Sort(grv.Columns[0],ListSortDirection.Ascending);
for ( int row = 0; row < grv.Rows.Count; row++)
{
for ( int col = 0; col < grv.Columns.Count; col++)
{
int rowx=1;
if (grv.Rows[row].Cells[col].Value != null && grv.Rows[row].Cells[col].Value.Equals(grv.Rows[rowx].Cells[col].Value))
{
if (col == grv.Columns.Count - 1)
{
grv.Rows.RemoveAt(row);
grv.Sort(grv.Columns[0], ListSortDirection.Descending);
}
}
else
{
grv.FirstDisplayedScrollingRowIndex = grv.RowCount - 1;
grv.Rows[grv.RowCount - 1].Selected = true;
}
}
}
}
Upvotes: 3
Views: 15984
Reputation: 17402
for (int currentRow = 0; currentRow < grv.Rows.Count; currentRow++)
{
var rowToCompare = grv.Rows[currentRow]; // Get row to compare against other rows
// Iterate through all rows
//
foreach (var row in grv.Rows)
{
if (rowToCompare.equals(row) continue; // If row is the same row being compared, skip.
bool duplicateRow = true;
// Compare the value of all cells
//
for (int cellIndex; cellIndex < row.Cells.Count; cellIndex++)
{
if ((null != rowToCompare.Cells[cellIndex].Value) &&
(!rowToCompare.Cells[cellIndex].Value.equals(row.Cells[cellIndex].Value)))
{
duplicateRow = false;
break;
}
}
if (duplicateRow)
{
grv.Rows.Remove(row);
}
}
}
Upvotes: 2
Reputation: 1
try
{
if (dgv_Language.Rows.Count > 2)
{
for (int currentRow = 0; currentRow < dgv_Language.Rows.Count; currentRow++)
{
var rowToCompare = dgv_Language.Rows[currentRow]; // Get row to compare against other rows
// Iterate through all rows
//
foreach (DataGridViewRow row in dgv_Language.Rows)
{
if (rowToCompare.Equals(row))
{
continue;
}
// If row is the same row being compared, skip.
bool duplicateRow = true;
// Compare the value of all cells
//
if (rowToCompare.Cells[0].Value != null && rowToCompare.Cells[0].Value.ToString() != row.Cells[0].Value.ToString())
{
duplicateRow = false;
}
if (duplicateRow)
{
dgv_Language.Rows.RemoveAt(row.Index);
break;
}
}
}
}
}
catch
{
}
Upvotes: -1
Reputation: 352
This is cleaner and involves less compare.
public void RemoveDuplicate(DataGridView grv)
{
for (int currentRow = 0; currentRow < grv.Rows.Count - 1; currentRow++)
{
DataGridViewRow rowToCompare = grv.Rows[currentRow];
for (int otherRow = currentRow + 1; otherRow < grv.Rows.Count; otherRow++)
{
DataGridViewRow row = grv.Rows[otherRow];
bool duplicateRow = true;
for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
{
if (!rowToCompare.Cells[cellIndex].Value.Equals(row.Cells[cellIndex].Value))
{
duplicateRow = false;
break;
}
}
if (duplicateRow)
{
grv.Rows.Remove(row);
otherRow--;
}
}
}
}
Upvotes: 4