4

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;
Darren
  • 68,902
  • 24
  • 138
  • 144

1 Answers1

3

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
}
Darren
  • 68,902
  • 24
  • 138
  • 144
  • Cannot implicitly convert type 'System.Data.DataRow' to 'bool –  May 22 '12 at 15:55
  • Table doesn't have a primary key. I don't want a primary key in this case. –  May 22 '12 at 17:17
  • You need to set the PrimaryKey property of your DataTable object before you call Find DataColumn[] keyColumns = new DataColumn[1]; keyColumns[0] = dt.Columns[""]; dt.PrimaryKey = keyColumns; – Hussain Dec 23 '15 at 09:00