0

我想这样做,以便根据用户在 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
4

2 回答 2

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
于 2013-06-24T14:58:51.097 回答
2

selectedItems 包含 DataGridViewRow 对象的列表,而不是 DataGridViews。更新如下:

For Each selectedItem As DataGridViewRow In selectedItems
于 2013-06-24T14:58:52.663 回答