Drag and drop from a datagridview to another
Hello,
I'm having problems with drag and drop of a cell value (copy) from one datagridview to another, because id drops two cells below of the point I release the mouse. I calculated the difference of the hittest "y" coordinate and it's 50 pixels. The strangest thing is, that difference increases exponentially if the form is not maximized.
The purpose of the code below, is to copy the value of a cell in OriginGrid to a specific cell on DestinationGrid. I belive the problem has to do with the "hittest" being relative but I can't figure out why. Any ideas?
Private
Sub OriginGrid_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles OriginGrid.MouseDown Dim hit As DataGridView.HitTestInfo = OriginGrid.HitTest(e.X, e.Y) If hit.Type = DataGridViewHitTestType.Cell ThenclickedCell = OriginGrid.Rows(hit.RowIndex).Cells(hit.ColumnIndex)
OriginGrid.DoDragDrop(clickedCell.Value, DragDropEffects.Copy)
End If End Sub Private Sub DestinationGrid_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DestinationGrid.DragDrop Dim hit As DataGridView.HitTestInfo = DestinationGrid.HitTest(e.X, e.Y) If hit.Type = DataGridViewHitTestType.Cell ThenclickedCell = DestinationGrid.Rows(hit.RowIndex).Cells(hit.ColumnIndex) 'rowindex is two cells below on a maximized form...
clickedCell.Value = e.Data.GetData(DataFormats.Text).ToString
End If End Sub Private Sub DestinationGrid_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DestinationGrid.DragEnter If (e.Data.GetDataPresent(DataFormats.Text)) Thene.Effect = DragDropEffects.Copy
Elsee.Effect = DragDropEffects.None
End If End Sub
Answers
Ok, I found the answer: the position is indeed relative so instead of
Dim hit As DataGridView.HitTestInfo = DestinationGrid.HitTest(e.X, e.Y)
I had to write something like:
Dim
hit As DataGridView.HitTestInfo = DestinationGrid.HitTest(MousePosition.X - Me.Location.X - 3, MousePosition.Y - 54 - Me.Location.Y)These parameters are for a regular form with a menubar on top (54).
All Replies
- Sorry,
I forgot the following line on top of the module:
Private clickedCell As DataGridViewCell
Ok, I found the answer: the position is indeed relative so instead of
Dim hit As DataGridView.HitTestInfo = DestinationGrid.HitTest(e.X, e.Y)
I had to write something like:
Dim
hit As DataGridView.HitTestInfo = DestinationGrid.HitTest(MousePosition.X - Me.Location.X - 3, MousePosition.Y - 54 - Me.Location.Y)These parameters are for a regular form with a menubar on top (54).
Hi balves,
Could you tell me how your datagridview columns were set up?
Thanks,
dave_sky
- What you could also do is to translate screen coordinates to client coordinates. It would look something like this:
Point clientPoint = DestinationGrid.PointToClient(new Point(e.X, e.Y));
DataGridView.HitTestInfo hit = DestinationGrid.HitTest(clientPoint.X, clientPoint.Y);
Hope that helps.

