Click here to Skip to main content
15,741,692 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm trying to drag/drop a file from Windows Explorer into a datagridview cell. The end result should be that the file name should appear in the selected cell. I got everything to work except for the fact that the file name gets copied into the wrong datagridview cell. For example, if I try to drag and drop into cell c1,r1, the data goes into c1,r3. It seems pretty consistent that it always goes 2 rows below where I drop it. Here is what I got so far:

Private Sub FormDGVTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim DT As New DataTable


        For x As Integer = 0 To 10
            DT.Rows.Add(x, x + 2, x + 4, x + 6)
        Me.DataGridView1.DataSource = DT

End Sub

Private Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop

        Dim cellvalue As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())

        If cellvalue.Length > 1 Then
            MsgBox("You can only drag and drop one file at a time", MsgBoxStyle.Information, "One file only")
            Exit Sub
        End If

        Dim cursorLocation As Point = Me.PointToClient(New Point(e.X, e.Y))
        Dim hittest As System.Windows.Forms.DataGridView.HitTestInfo = DataGridView1.HitTest(cursorLocation.X, cursorLocation.Y)

        If hittest.ColumnIndex <> -1 AndAlso hittest.RowIndex <> -1 Then
            DataGridView1(hittest.ColumnIndex, hittest.RowIndex).Value = cellvalue(0)
        End If

End Sub

Private Sub DataGridView1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragOver

        e.Effect = DragDropEffects.Copy

End Sub

Any ideas why this is not working?

Solution worked great....thanks
Share this answer
Dim cursorLocation As Point = Me.PointToClient(New Point(e.X, e.Y))

should be:
Dim cursorLocation As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900