开发者

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, EventA开发者_JAVA百科rgs 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜