Switch for selected control in common event ?

F

Frank Esser

Hi !

I have several buttons and a common click event for all of them. How can I
get the reference to the clicked control in a switch?

This does not work:

private void Button_Click(object sender, System.EventArgs e)
{
switch ((Button)sender)
{
case Button1:
...
break;
case Button2:
....
break;
default:
break;
}
}
 
M

Morten Wennevik

Hi Frank,

Since the Button1 reference may change you can't use it in a switch, only const variables allowed.

You need to use if/else if/else blocks.
 
T

The Crow

you can give ur buttons Tag property different values and switch.
ur code would be like :
 
J

James Curran

You can use the Name property:

switch( ((Button)sender).Name)
{
case "Button1":
// :
break;
case "Button2" :
// :
break;
}

But the real answer is.... If you want to do something different for
each button, you should be using separate Click events. Factor the common
part into a separate method, and call it from each of the Button[n]_Click
events.


--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top