tags:

views:

44

answers:

2

My form has several numeric up down controls. All of these controls, when changed, call the same method:

    private void SetColors(object sender, EventArgs e)

How do I determine which control called the method?

+1  A: 

The control on that the event occured is stored in the variable sender. You just need to cast it back to its original type.

Jens
+4  A: 

That's what the sender parameter is for.

If you know the time, you can cast it appropriately:

NumericUpDownControl control = (NumericUpDownControl) sender;

If it could be any of several types, you can use as and a null test, or is followed by a cast.

Of course, you only need to cast to the type which contains the members you need - so you could potentially just cast to Control, for example.

EDIT: Suppose you just want the name, and you know that the sender will always be a control of some kind. You can use:

private void SetColors(object sender, EventArgs e)
{
    Control control = (Control) sender;
    String name = control.Name;
    // Use the name here
}
Jon Skeet
Thanks, Jon. I am just learning C#, so could you include a sample line of code to illustrate what you mean? It would be ideal to obtain the name of the calling control.
Jimmy
@Jimmy: Okay, I've given an example here. If you could give more details about what you want to happen, we may be able to help you more.
Jon Skeet
Jon, that solved my problem. I really appeciate your help.
Jimmy