Search code examples
vb.netminesweeper

Clicking on the form causes 'Unable to cast object of type '<Namespace.FormName>' to type 'System.Windows.Forms.Button'


I am making a version of the Microsoft game 'Minesweeper'. I make the buttons and labels programmatically and add two handlers for the buttons and one handler for the labels as follows.

AddHandler Newbtn.MouseDown, AddressOf Button_MouseDown
AddHandler Newbtn.MouseUp, AddressOf Button_MouseUp
AddHandler Newlbl.MouseDown, AddressOf Label_MouseDown

then I have three procedures:

Private Sub Button_MouseUp(sender As Button, e As MouseEventArgs) Handles Me.MouseUp
 Private Sub Button_MouseDown(sender As Button, e As MouseEventArgs) Handles Me.MouseDown
Private Sub Label_MouseDown(sender As Label, e As MouseEventArgs) Handles Me.MouseClick

Everything works fine until I click outside of the grid of buttons on the form itself, when I get a 'invalidcastexception'. VS2015 goes into a break state. At the top it says:

"Your Application has entered a break state, but there is no code to show because all threads were executing external code(typically system or framework code)."

Additional information: Unable to cast object of type 'Mines.MineSweeperPJS' to type 'System.Windows.Forms.Button'.

Mines is the Namespace. MineSweeperPJS is the form.

Any suggestions as to the cause of this issue would be greatly appreciated!


Solution

  • The problem is in this part of your event handlers

    ..... Handles Me.MouseUp
                 ^^^
    

    this means that every mouseup, or mousedown event on your form (Me) are passed to the event handler specified.
    I think that you have written this event handler manually changing the parameter sender from Object to Button because if you let the Form Designer use its own template you end up with something like this

    Private Sub Button_MouseUp(sender As Object, e As MouseEventArgs) Handles Newbtn.MouseUp
    

    When the form engine calls these event handlers, in response to a Form mousedown or mouseup it passes the reference to the Form itself (Me) and not the reference to a Button. And this is the reason of the invalid cast.

    You could remove the ...Handles Me.MouseUp because you have already set up the event handlers using the AddHandler and also restore the sender parameter to be As Object