c# - 将 DataGridViewRow 转换为 DataRow

标签 c# vb.net datagridview

我在其他地方看到过此问题的解决方案,但它们都使用将 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

问题是,如果您这样做是为了将数据从一个表复制到另一个表,您会收到错误消息“此行已属于另一个表”。有没有办法实际复制这一行,而不是引用它?我宁愿不必只遍历每个单元格,复制它的 Value 属性。有更好的方法吗?

使用 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

最佳答案

请参阅此链接:http://support.microsoft.com/kb/308909

您需要使用 ImportRow() 方法。

关于c# - 将 DataGridViewRow 转换为 DataRow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1438770/

相关文章:

c# - 我可以在 C# 泛型约束中指定 'supertype' 关系吗?

c# - linq "System.NotSupportedException"有错误

c# - 在数据库中插入 datagridview 的值

c# - 如何在按下按钮后刷新datagridview

c# - 如何使用 Fluent NHibernate 和多个数据库识别特定实体的 session 工厂

c# - 你能通过内存位置而不是内容来比较字符串吗?

vb.net - 使用 VB.NET 执行存储过程

vb.net - vb.net 中的类出现问题

.net - 更新 VB.NET 中的 MySQL 字段

c# - 从分离的类到 winform 显示带有 DataSet 的数据库项目到 Datagridview