C # combines 2 events in one way

I am relatively new to programming as you will see soon ...
I have 2 events that execute the same code. I currently have the following pseudocode for datagridview:

private void dgv_CellEnter(object sender, DataGridViewCellEventArgs e) { string abc = "abc"; } private void dgv_CellClick(object sender, DataGridViewCellEventArgs e) { string abc = "abc"; } 

Is there a way to combine this into one event? Is there a better way to do this?

+5
source share
5 answers

Why not just use one method and match it with two events?

 private void dgv_CellEvent(object sender, DataGridViewCellEventArgs e) { string abc = "123"; } // In the event mapping dgv.CellEnter += dgv_CellEvent; dgv.CellClick += dgv_CellEvent; 
+7
source

Well, the quick answer is yes. Put the gut methods in your own method, and then just call the onclick event call. This will give you only one place to update the code if you need to change it.

There are 100 different ways to do this, and this is easiest.

So create something like this:

 protected void MyNewMethod() { string abc = "123"; } 

and then your other methods will simply call it like this:

 private void dgv_CellEnter(object sender, DataGridViewCellEventArgs e) { MyNewMethod(); } private void dgv_CellClick(object sender, DataGridViewCellEventArgs e) { MyNewMethod(); } 

Option 2

Just call the same method from the markup. You really only need one of these methods, and the event in the markup can cause the same thing.

+6
source

In the properties window (using C # Express) you can select event handlers in the drop-down list or manually enter the name of the method. The signature just needs to match. I guess this is the same in VS.

+2
source

The easiest way to do this:

 private void dgv_CellEnter(object sender, DataGridViewCellEventArgs e) { dgv_CellClick(sender, e); } private void dgv_CellClick(object sender, DataGridViewCellEventArgs e) { string abc = "abc"; } 

There is code that is automatically generated by the IDE that binds your events, but you can change this so that they both connect the same event handler, but I don’t like messing with the generated code.

In ASP.NET or WPF, your data grid or similar property has a property that defines the name of the event handler, so you can just point to both of them.

If you programmed in VB.NET instead of C #, you could just write one method and use the Handles keyword to say that this one method handles both events.

+1
source

You can try the following:

 private void dgv_CellEnter(object sender, DataGridViewCellEventArgs e) { string abc = "abc"; } private void dgv_CellClick(object sender, DataGridViewCellEventArgs e) { dgv_CellEnter(sender, e); } 

That way, when you either press or press Enter, it will run the same method.

thanks

+1
source

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


All Articles