user1108948
user1108948

Reputation:

Avoid adding duplicate datarows

In my Windows Forms Application, basically I have two DataGridViews. I want to select rows from right one and add selected rows to the left. The right DataGridViewhas a checkbox column.

See the image :


Grids


For example :


  1. Click the first row and Click Add button.

  2. Click the third row and Click Add button.

The problem is the first row was added twice because it was ticked.

How can I make sure that rows added are distinct?


My Code:


foreach (DataGridViewRow row in dgRight.Rows)
{
    DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
    if (check.Value != null)
    {
        if ((bool)check.Value)
        {
            DataRow myRow = (row.DataBoundItem as DataRowView).Row;
            DataRow dr = dt.NewRow();
            dr[0] = myRow[0];
            dr[1] = myRow[1];
            dr[2] = myRow[2];
            dr[3] = myRow[3];

            dt.Rows.Add(dr);
        }
    }
}
dgLeft.DataSource = dt;

Upvotes: 4

Views: 5121

Answers (1)

Darren
Darren

Reputation: 70806

Check if the row already exists in the Data Table by using the .Find method:

var rowExists = dt.Rows.Find(dr);

if (rowExists == null) { // The row doesn't exist
  dt.Rows.Add(dr); // Add the row
}

Upvotes: 3

Related Questions