Identify who invokes Event Handler

房东的猫 提交于 2019-12-02 12:24:41

问题


I have my app with my labels written to centralize when its text was modified.

To make that I invoke a method through an EventHandler. I want to use same method to each one of my labels, but I don´t know how to identify in the method which label invoke it.

If I have a code like this:

       lbl_TextChanged(object sender, EventArgs e)
        {
           ..code..
           label1.Location = new Point("label's location");
           ..more code..
        }

and I invoke again that method from another label, how could I modify that code in order to know which label invoke it?

SOLUTION Thanks for the help, This is the first time I tried to make something with the event handler and didn't know that I need to cast the sender. That solves my problem.

Thanks for the help!


回答1:


The sender object in the event handler signature is the control that raised the event.

Simply cast this object and you have access to all the control's information.

Label label = sender as Label;

You do need to be a little bit careful with this, since you are assuming that only controls of type Label are raising events that have this handler method.




回答2:


That's what the sender is for:

Point p = ((Label)sender).Location;
// adjust p 
label1.Location = p;


来源:https://stackoverflow.com/questions/10821688/identify-who-invokes-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!