将DataGridViewRow转换为DataRow

4

我曾经在其他地方看到过解决方法,但他们都使用了将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
1个回答

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接