我想这样做,以便根据用户在datagridview中选择的行创建新的数据表,但是我不断收到错误Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Windows.Forms.DataGridView
我不知道这意味着什么,我希望能得到一些帮助。
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
答案 0 :(得分:3)
替换
For Each selectedItem As DataGridView In selectedItems
dt2.Rows.Add(n)
dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
Next
使用
For Each selectedItem As DataGridViewRow In selectedItems
dt2.Rows.Add(selectedItem)
' dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
Next
答案 1 :(得分:2)
selectedItems包含DataGridViewRow对象的列表,而不是DataGridViews。更新到以下内容:
For Each selectedItem As DataGridViewRow In selectedItems