我曾经在其他地方看到过解决方法,但他们都使用了将DataRowView设置为我的DataGridViewRow.DataBoundItem的想法,然后使用DataRowView.Row属性(如下面的代码所示)。
这是我的代码:
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
问题在于,如果您这样做是为了从一个表复制数据到另一个表,您会收到错误“此行已属于另一个表”。是否有办法实际复制此行而不是引用它?我不想只循环每个单元格,复制其值属性。有更好的方法吗?
使用NYSystemsAnalyst建议的解决方案:
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