0

I am getting following exception while coping the row in same datagrid view control System.InvalidOperationException was unhandled Message="Row provided already belongs to a DataGridView control." Following is copy method that copies selected rows in in currentRowCollection as DataGridViewSelectedRowCollection

copy()
     {
            If (DataGridViewWorkGroupDetails.Rows.Count = 1) Then
                Exit Sub
            End If
            Try
                pasteMode = "copy"
                currentRowCollection = DataGridViewWorkGroupDetails.SelectedRows
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "frmworkgroup:copyRowCollectionError")
            End Try
       }

And in paste method

paste()
{
  Dim row As DataGridViewRow
  Dim myRow As DataGridViewRow
        For Each row In currentRowCollection
            myRow = row
            myRow.Cells.Item(1).Value = String.Empty
            DataGridViewWorkGroupDetails.Rows.Insert(DataGridViewWorkGroupDetails.Rows.Count - 1, myRow)
        Next

}

During paste in paste method i want to remain 1th column as empty string .. When I copy the row from one datagridview to another it works but when I copy to same datagridview then it adds exception.Row provided already belongs to a DataGridView control

Coder Guru
  • 513
  • 3
  • 18
  • 37

1 Answers1

0

The problem is you are using a reference to a datarow. The row in

For Each row In currentRowCollection

is actually a reference to the row that already exists in the dataview.

You need to do a deep copy of the data in the row before you call the insert.

myRow = DataGridViewWorkGroupDetails.NewRow();
myRow.ItemArray = row.ItemArray;
DataGridViewWorkGroupDetails.Rows.Add(myRow);

I haven't tested this code, but it should work

Lee Baker
  • 562
  • 1
  • 3
  • 12
  • its not working in vb.net ..There is no NewRow() method for the datagridview which used in the line above for myRow = DataGridViewWorkGroupDetails.NewRow(); – Coder Guru Feb 14 '12 at 07:36