• Twitter
  • Facebook
  • Google+
  • Instagram
  • Youtube

Friday, March 16, 2007

Use Delegate and Events in Asp.Net

I'm explaining Delegates and Event with the use of UserControl and Form in the Asp.Net Webpage.

Steps for usercontrol

1. First create one user control (Like ucTestDelegate)

2. Declare one Delegate (dont declare it in with in function but declare it in class)

3. Declare one event that uses this delegate (Declare it in class)

4. signature of event and Delegate function must match

// Declare one Delegate with its signature means with its return types and parameters.
public delegate void TestDelegateHandler(object sender, EventArgs e);

//Declare one Event that handle by our Delegate.
public event TestDelegateHandler TestDelegateFunction;

protected void Page_Load(object sender, EventArgs e)
protected void btnSend_Click(object sender, EventArgs e)
this.lblMessage.Text = "Send Button Pressed";
TestDelegateFunction(sender, e);

Steps for Form

1. Drag this usercontrol into page.
2. now Declare one function that has the same name and same Signature as the delegate have.
Example :

private void UcTestDelegate1_TestDelegateFunction(object sender, EventArgs e)
lblMessage.Text = " Page Label contains : " + "
" + "Test Delegate Function Calls";

3. Now in page load event of page Use the += operator to associate an event with an instance of a delegate that already exists.

protected void Page_Load(object sender, EventArgs e)
UcTestDelegate1.TestDelegateFunction +=new ucTestDelegate.TestDelegateHandler(UcTestDelegate1_TestDelegateFunction);

4. When you run Form And press send Button First the event of usercontrol calls and then of form. (To see how it calls debug both the events).

That's It !
Good Luck.



Get in touch with me


12 Street West Victoria 1234 Australia

Phone number

+(12) 3456 789