How to raise an event using addHandler

I am comfortable with Vb.Net events and handlers. Can someone help me with how to create event handlers in C # and create events.

+6
c # handler events
source share
4 answers

Developers who know only C # or only VB.Net may not know that this is one of the big differences between VB.NET and C #.

I shamelessly copy this nice explanation of VB events: VB uses declarative syntax to add events. In the code that will handle the event, a Handles clause appears . If necessary, several methods can process the same event, and several events can be processed by the same method. Using the Handles clause relies on the WithEvents modifier, which appears in the declaration of a base variable, such as a button. You can also attach property handlers using AddHandler and remove them using RemoveHandler. for example

Friend WithEvents TextBox1 As System.Windows.Forms.TextBox Private Sub TextBox1_Leave(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles TextBox1.Leave 'Do Stuff ' End Sub 

In C #, you cannot use declarative syntax. You use + =, which is overloaded to act as a VB.Net AddHandler. Here's an example of shamelessly stolen from tster answer :

 public MyClass() { InitializeComponent(); textBox1.Leave += new EventHandler(testBox1_Leave); } void testBox1_Leave(object sender, EventArgs e) { //Do Stuff } 
+10
source share

In C # 2 and above, you add event handlers as follows:

 yourObject.Event += someMethodGroup; 

If the signature of someMethodGroup matches the signature of yourObject.Event delegate.

In C # 1, you need to explicitly create an event handler like this:

 yourObject.Event += new EventHandler(someMethodGroup); 

and now the method group, event, and EventHandler must match.

+4
source share
  public MyClass() { InitializeComponent(); textBox1.LostFocus += new EventHandler(testBox1_LostFocus); } void testBox1_LostFocus(object sender, EventArgs e) { // do stuff } 
+3
source share

All Articles