There is a ColorChange method that changes the color of the label ... it has two parameters

 public void ColorChange(object sender, EventArgs e) 

How do I get the name of the object that accessed the method?

  • What is an "object name"? - Igor
  • If you know that a Button is appealing there or someone else, then var button = (Button)sender; Well, get all the parameters of the desired button, including the name. button.Name - EvgeniyZ
  • @EvgeniyZ Thank you, your answer helped me a lot! - Arthur_Zhilinskiy
  • @Arthur_Zhilinskiy Let's close the question then. Now answer this issue, accept. - EvgeniyZ

1 answer 1

When you subscribe to an event, you create a method that executes. In your case, it is public void ColorChange(object sender, EventArgs e) . Inside, 2 values ​​are usually transmitted, one of which is sender , it is an object that is responsible for who exactly initiated this event.

So, if we bring this sender object to the necessary type, we can get the necessary values ​​(name, tag, content, etc.). How to set the type ?:

  1. var button = (Button)sender - here we indicated that sender is our button. But, here we must not forget to check the received button on Null , otherwise there may be problems later. That is, we must specify something like if (button != null) .

  2. if (sender is Button button) - here we indicate the type and at the same time we do a check on Null , conveniently and briefly. But on older versions of the language like this method does not work.