简体   繁体   中英

Get name of control calling method

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?

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM