9

I am comfortable with Vb.Net events and handlers. Can anybody will help me with how to create event handlers in c#, and raise events.

MarkJ
  • 30,070
  • 5
  • 68
  • 111
Mitesh
  • 119
  • 1
  • 1
  • 4
  • You need to be more specific. – tster Sep 28 '09 at 18:35
  • 2
    I think he just wants to know how to add event handlers and raise events in C#, and he already knows how to do it in VB. – Meta-Knight Sep 28 '09 at 19:44
  • Mitesh, I edited your question quite a lot. I was just trying to improve the English. If I've misunderstood what you were asking, I'm sorry - please just change it back. – MarkJ Sep 28 '09 at 19:47

4 Answers4

13

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

I will shamelesssly copy this nice explanation of VB events: VB uses a declarative syntax for attaching events. The Handles clause appears on the code that will handle the event. When appropriate, multiple methods can handle the same event, and multiple events can be handled by the same method. Use of the Handles clause relies on the WithEvents modifier appearing on the declaration of the underlying variable such as a button. You can also attach property handlers using the AddHandler keyword, and remove them with 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 can't use the declarative syntax. You use += which is overloaded to act like the VB.Net AddHandler. Here's an example shamelessly stolen from tster's answer:

public MyClass()
{
    InitializeComponent();
    textBox1.Leave += new EventHandler(testBox1_Leave);
}

void testBox1_Leave(object sender, EventArgs e)
{
  //Do Stuff
}
Community
  • 1
  • 1
MarkJ
  • 30,070
  • 5
  • 68
  • 111
8

In C# 2 and up you add event handlers like this:

yourObject.Event += someMethodGroup;

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

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

yourObject.Event += new EventHandler(someMethodGroup);

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

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
3
    public MyClass()
    {
        InitializeComponent();
        textBox1.LostFocus += new EventHandler(testBox1_LostFocus);
    }

    void testBox1_LostFocus(object sender, EventArgs e)
    {
        // do stuff
    }
tster
  • 17,883
  • 5
  • 53
  • 72