Is there a way to add event handlers for controls in C # without using a constructor?

I recently started working with C # and wondered if there is an easier way to create event handlers for controls. For example, if I have a button on a web form that needs a click handler, I simply open the designer and double-click on it, and it is created and connected for me. If I did not have the opportunity to use the constructor, what other way would it be to create it, except by hand? For example, in VB, all controls are displayed in the drop-down list of the code window, so you can select them, select an event and cut it out for you. Is there something similar in C #, or am I stuck doing this with difficulty?

+3
source share
4 answers

You can do the work that the designer does for you yourself, of course. Just add:

button1.Click += new System.EventHandler(button1_Click);

and create a suitable method to call:

private void button1_Click(object sender, EventArgs e) { // button1 was clicked }
+6
source

Why is it so complicated? Just write

yourComponent.YourEvent += >Cursor is here<

And now you should see a hint that by clicking [tab], you will get a method implementation for this particular event.

Nice and easy. No need to contaminate navigational dropdown materials that are not there .; -)

+4
source

EventHandler???

button1.Click += MyHandler;

private void MyHandler(object sender, EventArgs args)
{
}

# 3.0

button.Click += (sender, args) => Handler();
+2

lambdas, , , , .

:

radioButtonLeft.Click += new EventHandler((sender, e) => CallSomeMethod(1));

This is the easiest way I've found.

+1
source

Source: https://habr.com/ru/post/1721503/


All Articles