[英]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. 这就是
sender
参数的用途。
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. 如果它可以是几种类型的,你可以使用
as
和空测试,或者is
随后铸造。
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. 当然,您只需要转换为包含所需成员的类型 - 例如,您可能只是转换为
Control
。
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
. 发生事件的控制存储在变量
sender
。 You just need to cast it back to its original type. 您只需将其转换回原始类型即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.