We can't be sure exactly where the problem occurs, but since there are only two different direct casts in there (and the second is trivial) it has be the attempt to cast
btnSender
to a
Button
that throws the exception.
Unfortunately, we can't see what
btnSender
contains at all, or where it comes from, and thus there is nothing we can do to directly help you.
So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.
Put a breakpoint on the first line in the function, and run your code through the debugger. Then you can look at what you are expecting to be a Button and find out what it actually is. Then you can use the Stack trace to follow back to find out why it isn't what you expected.
Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.
Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
And when you've worked out why it isn't, I'd suggest you use this form instead to catch similar problems in a better way:
if (btnSender is Button b)
{
if (currentButton != b)
{
...
}
}
else
{
throw new ArgumentException($"Unexpected type in btnSender: expected a button, but got {btnSender.GetType()}");
}