Reputation: 861
I want to make it so a new datatable gets created based on what rows the user selects in the datagridview, however I keep getting an error saying Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Windows.Forms.DataGridView
I have no clue what this means, and I was hoping I could get some help.
Private Function getCoordinates()
Dim dt2 As New DataTable
'Dim r As DataRow
Dim n As Integer
Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
dt = dgv.DataSource
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
dgv.MultiSelect = True
dt2.Columns.Add("Position")
Try
For Each selectedItem As DataGridView In selectedItems
dt2.Rows.Add(n)
dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
Next
Catch ex As Exception
MsgBox("Error", MsgBoxStyle.Exclamation, "Error!")
End Try
Return dt2
Upvotes: 0
Views: 159
Reputation: 9193
selectedItems contains a list of DataGridViewRow objects, not DataGridViews. Update to the following:
For Each selectedItem As DataGridViewRow In selectedItems
Upvotes: 2
Reputation: 538
Replace
For Each selectedItem As DataGridView In selectedItems
dt2.Rows.Add(n)
dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
Next
With
For Each selectedItem As DataGridViewRow In selectedItems
dt2.Rows.Add(selectedItem)
' dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
Next
Upvotes: 3