Add an event handler to a control programmatically.

First we declare a Button named myButton:

Dim myButton As Button = New Button()
 myButton.ID = "btnMyButton"
 myButton.Text = "Just Do It!"

Here is how we add a handler to its click event:

 AddHandler myButton.Click, AddressOf myButton_Click

And last thing to do is write the actual method that handles the click event:

Protected Sub myButton_Click(ByVal sender As Object, ByVal e As EventArgs)

 'Your code goes here.

 End Sub

Here is how you can create an event in C#. I will briefly describe how the event is being created, how we raise the event and how add an eventhandler to it.

// we declare the delegate for the event; this is just the signature of
// a method, that will handle the event.
public delegate void Del(object sender, EventArgs e);
// then we declare the event object which holds the type of Del
//(the delegate we declared earlier) 
public event Del ev;
// We now add an EventHandler to the event being raised.
ev += new Del(SomeMethodName);
// And this is the method that will handle our event
void SomeMethodName(object sender, EventArgs e){
throw new NotImplementedException();}

// We trigger the event like this:
ev(sender, e);

 

Advertisement
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s