Using 'sender' in switch statement
Is there any way in which an attribute of 'sender' in an event can be used in a 'switch' header'.
I find that I can use 'sender' like this :- if (sender == Pentagon) OK but if I try to use 'sender' like this I get an error :- ' switch (sender)'. What I am wanting to do is something like this :-
private void ShapeMenu_Click(object sender, EventArgs e)
{
switch (sender)
case Pentagon:
break;
case Hexagon:
break
}
Re: Using 'sender' in switch statement
What is Pentagon (or Hexagon)? Is this an object of a class, or a name of a class?
Attach the definition of Pentagon & Hexagon please.
Re: Using 'sender' in switch statement
Pentagon and Hexagon are the names of the menu items clicked on.
Re: Using 'sender' in switch statement
This might work:
Code:
switch (sender)
{
case (object)Pentagon:
break;
case (object)Hexagon:
break;
}
But a better solution would be to simply create a separate event handler for each menu item.
Re: Using 'sender' in switch statement
I'm confused now :confused:
Your first post seems to imply that Pentagon and Hexagon are variable names as you say:
Quote:
Originally Posted by
owdcoder83
I find that I can use 'sender' like this :- if (sender == Pentagon) OK
This comparison would only be valid if Pentagon was a variable of type 'object', and if it was then a switch on sender should work also. But then you say
Quote:
Originally Posted by
owdcoder83
Pentagon and Hexagon are the names of the menu items clicked on.
which I take to mean that they are the values of the Name properties of MenuItem objects. Is this correct?
If it is, then you need to cast sender to a MenuItem, get the Name (which is a string) and then switch on this (you can switch on strings in C#)
Re: Using 'sender' in switch statement
Talkag - What you have suggested will not work , as soon as I type in 'switch ( sender)' the word sender is underlined in red signalling an error.
PeterB - What you say in your last two lines is exactly correct. How do you cast sender as a Menuitem. ? I am not sure how to do this.
Re: Using 'sender' in switch statement
Hi Talkag & PeterB - I have managed to solve the casting of sender to MenuItem and the switch now works. I did it as shown here :-
String nam = ((ToolStripMenuItem)sender).Text;
switch (nam)
{
case "Pentagon":