-
April 9th, 2012, 09:19 AM
#1
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
}
-
April 9th, 2012, 09:57 AM
#2
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.
-
April 9th, 2012, 04:08 PM
#3
Re: Using 'sender' in switch statement
Pentagon and Hexagon are the names of the menu items clicked on.
-
April 9th, 2012, 04:30 PM
#4
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.
-
April 9th, 2012, 04:35 PM
#5
Re: Using 'sender' in switch statement
I'm confused now
Your first post seems to imply that Pentagon and Hexagon are variable names as you say:
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
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#)
-
April 10th, 2012, 04:11 AM
#6
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.
-
April 10th, 2012, 05:04 AM
#7
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":
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|