Click here to Skip to main content
15,666,286 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
private void ActivateButton(object btnSender)

              if (btnSender != null)
                  if (currentButton != (Button)btnSender)
                      Color color = SelectThemeColor();
                      currentButton = (Button)btnSender;
                      currentButton.BackColor = color;
                      currentButton.ForeColor = Color.White;
                      currentButton.Font = new System.Drawing.Font("Arial", 12.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

What I have tried:

i have tried this code and give me error System.InvalidCastException.
Please help me to correct this
Updated 31-Jul-22 5:50am
0x01AA 31-Jul-22 11:40am    
It looks like object btnSender is not of type Button and the cast will fail here: if (currentButton != (Button)btnSender)

1 solution

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)
    throw new ArgumentException($"Unexpected type in btnSender: expected a button, but got {btnSender.GetType()}");
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900