Get control call method name

My form has several numeric controls from top to bottom. All of these controls, when changed, call the same method:

    private void SetColors(object sender, EventArgs e)

      

How do I determine which control has called?

+2


a source to share


2 answers


This is a parameter sender

.

If you know the time, you can do it accordingly:

NumericUpDownControl control = (NumericUpDownControl) sender;

      

If it can be any of several types, you can use as

both a null test, or is

followed by a cast.



Of course, you only need to specify the type that contains the members you want - so you can just cast to Control

eg.

EDIT: Suppose you just need a name and you know that the sender will always be in 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
}

      

+10


a source


The control for this event is stored in a variable sender

. You just need to cast it back to its original type.



+2


a source







All Articles