Having problem dragging and dropping a dynamically created set of PictureBoxes. I got most of this code of another VB forum and added my own to try and figure out what was happening, but now I'm getting a runtime error.
An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object.
VB.NET:
Public Class frmMain
Inherits System.Windows.Forms.Form
Dim DragPoint As Point
Private XOffset As Integer
Private YOffset As Integer
'Private gridOpp As New Grid(grpOppGrid)
Private gridYou As New Grid(grpYourGrid)
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim LV As Integer
Dim Cheeses(23) As PictureBox
'Our form will not be the only drag drop target this time.
Me.AllowDrop = True
'You can drag food to either of the two whelks.
'Now let's create a couple dozen pieces of cheese.
For LV = 0 To 23
Cheeses(LV) = New PictureBox
With Cheeses(LV)
.Name = "Cheese" & LV.ToString("G")
'Generate a quick name for it.
'.Image = Cheese.Image
'Give it the same image as the cheese image already on the form.
.Size = New Size(24, 24)
.SizeMode = PictureBoxSizeMode.StretchImage
'Make the cheese big.
.Location = New Point(24 * (LV Mod 4) + 250, 24 * (LV \ 4) + 20)
'Move it into a grid fashion.
End With
Me.Controls.Add(Cheeses(LV))
'Add this control to the form.
AddHandler Cheeses(LV).MouseDown, New System.Windows.Forms.MouseEventHandler(AddressOf AnyShip_MouseDown)
'Make each cheese event's mousedown be handled by the anycheese.
'This will probably be the closest that you can get to a control array.
Next
End Sub
Private Sub AnyShip_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseDown
Dim PB As PictureBox
PB = DirectCast(sender, System.Windows.Forms.PictureBox)
DragPoint = New Point(e.X, e.Y)
PB.DoDragDrop(PB, DragDropEffects.Move)
End Sub
Private Sub frmMain_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragEnter
Dim Cheeses(23) As PictureBox
If e.Data.GetDataPresent(Cheeses.GetType()) Then
e.Effect = DragDropEffects.Move
End If
End Sub
Private Sub frmMain_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragDrop
Dim PB As GroupBox
Dim Finalpoint As Point
Dim Cheeses(23) As PictureBox
PB = e.Data.GetData(Cheeses.GetType())
Finalpoint = New Point(e.X, e.Y)
Finalpoint = Me.PointToClient(Finalpoint)
Finalpoint.Offset(-DragPoint.X, -DragPoint.Y)
PB.Location = Finalpoint
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub grpYourGrid_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grpYourGrid.Enter
Me.AllowDrop = True
End Sub
Private Sub grpOppGrid_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grpOppGrid.Enter
Me.AllowDrop = True
End Sub
End Class