Plz Help Me to Solve this Error.. I am coding this to build a Calcuator in Vb.net....i have declared "b" as a Button.. how to resolve this error.. plz help..

error.jpg

Dani AI

Generated

A short diagnosis and safe fixes for the InvalidCastException shown in the screenshot.

An InvalidCastException means your code tried to convert an object to a type it is not (for example, treating a menu item or other control as a Button). This is a runtime type mismatch, not a math or UI bug — fix the cast or the event wiring rather than just hiding the error. (learn.microsoft.com)

Quick reproduction / debug steps (do these first):

  • Put a breakpoint in the handler and inspect sender.GetType().FullName (or print it with Debug.WriteLine) to see what actually fired the event.
  • Use a safe cast pattern so the code does not throw if the sender is not a Button; check the result before using it.

Example of a safe pattern to use in the handler:

Debug.WriteLine("Sender type: " & sender.GetType().FullName)

Dim btn = TryCast(sender, Button)
If btn Is Nothing Then
    Debug.WriteLine("Handler was invoked by: " & sender.GetType().FullName)
    Return
End If

' Use btn safely here (Text, Name, Tag, etc.)

TryCast returns Nothing instead of throwing when the conversion fails, so you can branch on that and handle non-button senders gracefully. Use it when a handler is shared by different control types. (learn.microsoft.com)

Practical fixes

  • Confirm which controls are wired to this handler (designer Handles clause or any AddHandler calls) and remove non-button hookups if the code assumes a Button.
  • If you intentionally share one handler for buttons and menu items, branch on the runtime type and handle each case. See the VB guidance on determining an object’s runtime type for quick reference. (learn.microsoft.com)

Notes: avoid single-letter names like b (use btnDigit, btnOp) to reduce confusion between a control instance and a local variable. Also, don’t use try/catch to hide InvalidCastException — fix the cause.

Recommended Answers

All 2 Replies

Or you can just do an explicit cast as

Dim b As Button = DirectCast(sender, Button)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.