Click here to Skip to main content
15,891,033 members
Articles / Programming Languages / SQL
Article

Drag and Drop on a Windows Form

Rate me:
Please Sign up or sign in to vote.
4.00/5 (7 votes)
29 Apr 2008CPOL4 min read 57.4K   2.4K   38   6
How to insert an image on a form in runtime mode, dragging it to the right position and by using a database retrieve the position and shape when starting the application up again
image002.jpg

Introduction

This is a part of a bigger project I’m working on and it is a test to see how things work out with drag and drop. It works just as I wanted and therefore I share it with you on the Code Project. The Code Project is a great community and I have personally learned a lot from you other guys.

Many of you have used drag and drop before, so for those of you who have, this is just another drag and drop application. The goal of the application was to learn how to insert an image on a form in runtime mode, dragging it to the right position and by using a database retrieve the position and shape when starting the application up again. I want to point out that it is possible to add any kind of controls, it depends on the definition. Dim MyPicturebox As New TextBox will add a text box to the form, but you maybe have to set other properties depending on which control you are adding.

What is implemented in the application?

  • The use of an access database. (The database is located in the Bin folder).
  • SQL calls to Insert, update, delete and read from a database.
  • Adding handlers to drag and drop an image on the form.
  • The code to add, move and delete an image on the form and from the database.
  • The use of a Tool Strip control.

How it Works

We have a Button to start Edit Mode. When clicking it a Tool strip control appears and we are in edit mode. When we click on a Tools Strip button an image is added to the form at a fixed location. After adding it to the form you can drag it to the desired position by clicking on it and hold down the left mouse button while dragging. The landscape image is there to show that you can place an inserted image over another image and also to have something nice to look at. The last inserted image will always be in the front.

The Code

After the form is loaded click “Set to Edit Mode” and the Tool Strip appears. We are now ready to add images at runtime.

The code for doing this is simple.

VB
Dim MyPicturebox As New PictureBox
Me.Controls.Add(MyPicturebox)

Then we are adding some properties.

VB
'Adding an image and properties for the image
            MyPicturebox.Location = New Point(40, 40)
            MyPicturebox.BringToFront()
            MyPicturebox.BackgroundImageLayout = ImageLayout.Stretch
 
            'Find out which button is pressed to insert the right image.
            Dim TagId As Integer = e.ClickedItem.Tag
 
            MyPicturebox.BackgroundImage = sender.Items.Item(TagId).Image
            MyPicturebox.Name = sender.Items.Item(TagId).ToolTipText
 
            MyPicturebox.Size = New System.Drawing.Size(40, 40)

After we have inserted a new image to the form we want to store the position and type of image in a database.

VB
' Insert position and name in the database.
   selectString = "Insert into tblInfo (PosX, PosY, Name) Values (" & _
             "'" & e.X & "'," & _
             "'" & e.Y & "'," & _
             "'" & MyPicturebox.Name & "')"
 
If conn.State = ConnectionState.Closed Then conn.Open()
 
Dim cmd = New OleDbCommand(selectString, conn)
cmd.executeNonQuery()
If conn.State = ConnectionState.Open Then conn.Close()

To keep track of the Id of the stored image we have to send a request to the database asking for the Id of the last added image. The Id is important for updating and deleting the image. Observe that I’m using the MyPicturebox.Tag property to store the Id of the image.

VB
'Find the corresponding Id from the database
 MyPicturebox.Tag = FindLastId()

And here is the function that is called.

VB
Private Function FindLastId() As String

        selectString = "Select max(id) FROM tblInfo"
        If conn.State = ConnectionState.Closed Then conn.Open()
 
        Dim cmd = New OleDbCommand(selectString, conn)
 
        Dim Id As String
        Id = cmd.ExecuteScalar()
 
        If conn.State = ConnectionState.Open Then conn.Close()
 
        Return Id
End Function

In the process of inserting the image we have to add some handlers to help us with the drag and drop. We are adding tree handlers. The mouse click, the mouse move and the mouse up like this.

VB
'Add handlers that will move the image on the screen
 AddHandler MyPicturebox.MouseDown, AddressOf MyMouseClick
 AddHandler MyPicturebox.MouseMove, AddressOf MyMouseMove
 AddHandler MyPicturebox.MouseUp, AddressOf MyMouseUp

The Mouse Click Handler

This event is handling two arguments. Right click and left click. We use the right click to remove the image from the form. Before removing the image a Message box pops up asking if you want to remove the selected image or not.

The left click is used to determine the location of the image and start dragging. The cursor is changed to a hand.

VB
' The handler for the MouseClick event
    Public Sub MyMouseClick(ByVal sender As Object,
        ByVal e As System.Windows.Forms.MouseEventArgs)

        ' Find out if it is in Drag and Drop mode
  If ToolStrip1.Visible = True Then

            'Prosedure to move an image from the workspace. Using Mousebutton right
            If e.Button = Windows.Forms.MouseButtons.Right Then

                Dim Response As MsgBoxResult = MsgBox(
                    "Do you want to remove this object",
                    MsgBoxStyle.YesNo, "Id = " & sender.tag)
                If Response = MsgBoxResult.Yes Then   ' User chose Yes.
                    'Remove from workspace
                    Me.Controls.Remove(sender)
                    'Remove from database
                    If conn.State = ConnectionState.Closed Then conn.Open()
                    selectString = "DELETE FROM tblInfo WHERE(Id =" & sender.Tag & ")"
                    cmd = New OleDbCommand(selectString, conn)
                    reader = cmd.ExecuteReader()
                    reader.Close()
                    If conn.State = ConnectionState.Open Then conn.Close()
 
                End If
 
            End If
 
            'Procedure to select the image
            If e.Button = Windows.Forms.MouseButtons.Left Then
                Me.Cursor = Cursors.Hand
                Dragging = True
                mousex = -e.X
                mousey = -e.Y
                Dim clipleft As Integer = Me.PointToClient(MousePosition).X -
                    sender.Location.X
                Dim cliptop As Integer = Me.PointToClient(MousePosition).Y -
                    sender.Location.Y
                Dim clipwidth As Integer = Me.ClientSize.Width - (
                    sender.Width - clipleft)
                Dim clipheight As Integer = Me.ClientSize.Height - (
                    sender.Height - cliptop)
                Windows.Forms.Cursor.Clip = Me.RectangleToScreen(
                    New Rectangle(clipleft, cliptop, clipwidth, clipheight))
                sender.Invalidate()
 
            End If
        End If
    End Sub

The Mouse Move Handler

This handler moves the image depending on the position of the cursor. You can see the image following the cursor.

VB
' The handler for the MouseMove event
    Public Sub MyMouseMove(ByVal sender As Object,
        ByVal e As System.Windows.Forms.MouseEventArgs)
        ' Find out if it is in Drag and Drop mode
        If RadioButton5.Checked = True Then
            If Dragging Then
                'move control to new position
                Dim MPosition As New Point()
                MPosition = Me.PointToClient(MousePosition)
                MPosition.Offset(mousex, mousey)
                'ensure control cannot leave container
                sender.Location = MPosition
            End If
        End If
    End Sub

The Mouse up Handler

The important thing here is that we have to store the new position in the database and for this purpose we use a SQL Update statement. The cursor is changed to an arrow.

VB
' The handler for the MouseUp event
    Private Sub MyMouseUp(ByVal sender As Object,
        ByVal e As System.Windows.Forms.MouseEventArgs)

        ' Find out if it is in Drag and Drop mode
  If ToolStrip1.Visible = True Then

            If Dragging Then
          'After dragging update the database with the new position X and Y
                selectString = "Update (tblInfo) Set " & _
                            "PosX=" & "'" & sender.Location.X & "'," & _
                            "PosY=" & "'" & sender.Location.Y & "'" & _
                            " WHERE Id=" & sender.tag & ""

                If conn.State = ConnectionState.Closed Then conn.Open()

                Dim cmd = New OleDbCommand(selectString, conn)
                cmd.executeNonQuery()
                If conn.State = ConnectionState.Open Then conn.Close()
 
                'End the dragging
                Dragging = False
                Windows.Forms.Cursor.Clip = Nothing
                sender.Invalidate()
            End If

            Me.Cursor = Cursors.Arrow
        End If
    End Sub

The only thing that is left is that when we start the application again we load the stored positions and type from the database using a SQL read statement and use the same technique as described earlier to add handlers and properties.

In the Form1_Load we fill in an Id fore all the Tool Strip buttons. Observe that this is not the same Id as the Id for the images.

VB
'Fill in an Id for the ToolStripButton
        Dim i As Integer
        For i = 0 To ToolStrip1.Items.Count - 1
            ToolStrip1.Items.Item(i).Tag = i
        Next

You can see it all in the Form1_Load procedure. It is well commented.

That’s all.

License

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


Written By
Web Developer
Norway Norway
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHave you done any work with this in silverlight? Pin
mattsampson28-Dec-09 5:56
mattsampson28-Dec-09 5:56 
Hi Sigurd,

Have you done any work with this in a web browser?
I work for a school and I'm thinking about a project based on this for class seating plans for the teachers.
We have an SQL DB with all the students and classes in, so it would be a case of perhaps using silverlight to pull out all the students photos & names from the SQL DB and allow the teacher to place them in whatever format they wished for the room, and then save that so any cover teacher could see who where the students should be sitting!

Have you done anything similar to this before or know someone who has?

Best wishes
Matt
AnswerRe: Have you done any work with this in silverlight? [modified] Pin
Sigurd Johansen4-Jan-10 11:10
Sigurd Johansen4-Jan-10 11:10 
Questionhow to select the portion of image and drag selected part of image of picturebox1 and drop it in picturebox2 Pin
Harish RajKumar29-May-08 22:56
Harish RajKumar29-May-08 22:56 
AnswerRe: how to select the portion of image and drag selected part of image of picturebox1 and drop it in picturebox2 Pin
Sigurd Johansen14-Jul-08 23:52
Sigurd Johansen14-Jul-08 23:52 
GeneralPlease check your DB code Pin
mav.northwind29-Apr-08 20:48
mav.northwind29-Apr-08 20:48 
GeneralRe: Please check your DB code [modified] Pin
Sigurd Johansen30-Apr-08 5:13
Sigurd Johansen30-Apr-08 5:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.