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..

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..

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):
sender.GetType().FullName (or print it with Debug.WriteLine) to see what actually fired the event. 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
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.
Jump to Post— Reverend Jim 6,681Or you can just do an explicit cast as
Dim b As Button = DirectCast(sender, Button)
Why not make "b" the same type as sender? Also, you can examine what the sender is with TypeOf as noted:
https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference//operators/typeof-operator
Or you can just do an explicit cast as
Dim b As Button = DirectCast(sender, Button)We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.