Converting a DataGridViewRow to a DataRow
See this link: http://support.microsoft.com/kb/308909
You need to use the ImportRow() method.
Seth Moore
Currently: I'm a software engineer doing front-end and backend development at a large e-commerce site. Experience: I have developed embedded systems, enterprise software, and commercial software libraries. #SOreadytohelp
Updated on June 27, 2022Comments
-
Seth Moore almost 2 years
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