views:

902

answers:

1

I've seen solutions to this else where, but they all use the idea of setting a DataRowView equal to my DataGridViewRow.DataBoundItem, then using the DataRowView.Row property (In my code below).

Here's my code:

Dim tblTemp As New DataTable()
Dim row As Windows.Forms.DataGridViewRow
Dim rowView As DataRowView

For Each row In grdLabels.SelectedRows
    If (row.Cells("Status").Value = Status.RECIEVED) Then
        rowView = DirectCast(row.DataBoundItem, DataRowView)
        tblTemp.Rows.Add(rowView.Row)
    End If
Next

The problem is that if you are doing this to copy data from one table to another, you get the error "This row already belongs to another table". Is there any way to actually copy this row, rather than referencing it? I would prefer not having to just loop through each cell, copying its Value property. Is there a better way of doing this?

Solution using NYSystemsAnalyst suggestion:

Dim tblTemp As New DataTable()
Dim row As Windows.Forms.DataGridViewRow
Dim rowView As DataRowView

If TypeOf grdLabels.DataSource Is DataTable Then
    tblTemp = CType(grdLabels.DataSource, DataTable).Clone()
End If

For Each row In grdLabels.SelectedRows
    If (row.Cells("Status").Value = Status.RECIEVED) Then
        rowView = DirectCast(row.DataBoundItem, DataRowView)
        tblTemp.ImportRow(rowView.Row)
    End If
Next
+3  A: 

See this link: http://support.microsoft.com/kb/308909

You need to use the ImportRow() method.

NYSystemsAnalyst
Works great! Thanks.
smoore