Dailycode.info

Short solution for short problems

Drag and drop in Windows.Net

I was looking for some drag and drop functionality. Between all the posts I managed to gather some usefull information. Here's the result:

The goal was to drag an image onto another image. Then I save the coordinates in the database. I have an image containing the ground plans of our company. On the left I have a list of several type of machinery. They would have to drag a machine onto the map and save the location. I'm just going to use a simple example below to illustrate the drag and drop in Windows.Net.

We'll use 3 events of the panel (or picturebox): mousedown, mousemove and mouseup. When the user presses the mouse down on the image, we set the isDragging flag to true. Then the MouseMove event kicks in. The location of the panel (or picturebox) is changed to the new coordinates. When we release the mousebutton, we set the isDragging to false. That all there is. In the MouseUp event I can save the coordinates to the database.

	private void panel3_MouseDown(object sender, MouseEventArgs e)
        {
            isDragging = true;
 
            currentX = e.X;
            currentY = e.Y;
        }
 
        private void panel3_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                panel3.Top = panel3.Top + (e.Y - currentY);
                panel3.Left = panel3.Left + (e.X - currentX);
            }
 
        }
 
        private void panel3_MouseUp(object sender, MouseEventArgs e)
        {
            isDragging = false;
        }

 

I used the example located here.