Mats Lycken development

.NET and web related blog posts

NAVIGATION - SEARCH

ASP.NET 101 - Part 1: Communication from User control to Page in ASP.NET

User controls are great for encapsulating both behavior and look. When you have some UI elements that you want to use in more than one place a User control is a great way to add reusability.

One problem that you can run into is how you add communication from the user control to the web page. Perhaps you have a button in a user control, and when you click it the web page should perform some action. If the button was on the page we would simply bind to the Clicked event on the button, but when it’s inside of the user control we don’t have access to the button.

Luckily it is really easy in .NET to add your own events. In this really simple example we will create a user control with a button that also has an event, ButtonClicked. We will then create a page that contains an instance of the user control and bind to the exposed event so that the page will know when the button has been clicked.

We begin with the user control:

EventControl.ascx

   1: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EventControl.ascx.cs" 
   2: Inherits="UserControl_Event_1.EventControl" %>
   3: <asp:Button runat="server" ID="ClickButton" Text="Click me!" 
   4:     onclick="ClickButton_Click" />

EventControl.ascx.cs

   1: using System;
   2: namespace UserControl_Event_1
   3: {
   4:     public partial class EventControl : System.Web.UI.UserControl
   5:     {
   6:         protected void ClickButton_Click(object sender, EventArgs e)
   7:         {
   8:             OnButtonClicked(EventArgs.Empty);
   9:         }
  10:         protected void OnButtonClicked(EventArgs e)
  11:         {
  12:             if (ButtonClicked != null)
  13:             {
  14:                 ButtonClicked(this, e);
  15:             }
  16:         }
  17:         public event EventHandler ButtonClicked;
  18:     }
  19: }

The markup doesn’t contain anything special, just a button where we’ve bound to the click event.

The code-behind file contains our event that is exposed:

public event EventHandler ButtonClicked;

When we want to trigger this event we use the method OnButtonClicked:

protected void OnButtonClicked(EventArgs e)
{
    if (ButtonClicked != null)
    {
        ButtonClicked(this, e);
    }
}

If no one has bound to the event ButtonClicked will be null so we need to check that before we trigger it.

It is common to use the naming convention used here. The event says what has happened, like Clicked. And the method we use to trigger the event is called On<Event name>, like OnClicked.

So in our click event for the button we trigger the event with the line:

OnButtonClicked(EventArgs.Empty);

In this example we won’t send any data along with the event so we can use the predefined event argument EventArgs.Empty.

You can also note that when we trigger the event we send along the object that triggered it, the first parameter to the event this. That way the page can check exactly which user control that triggered it by checking the sender argument in the event handler.

We will now create a page that will use our simple user control.

Default.aspx

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
   2:  Inherits="UserControl_Event_1._Default" %>
   3: <%@ Register src="EventControl.ascx" tagname="EventControl" tagprefix="uc1" %>
   4: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   5: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   6: <html xmlns="http://www.w3.org/1999/xhtml" >
   7: <head runat="server">
   8:     <title>Untitled Page</title>
   9: </head>
  10: <body>
  11:     <form id="form1" runat="server">
  12:     <div>        
  13:         <uc1:EventControl ID="EventControl1" runat="server" OnButtonClicked="EventControl1_ButtonClicked" />
  14:         <br />        
  15:         <asp:Label runat="server" ID="MessageLabel" />
  16:     </div>
  17:     </form>
  18: </body>
  19: </html>

Default.aspx.cs

   1: using System;
   2: using System.Web.UI;
   3: namespace UserControl_Event_1
   4: {
   5:     public partial class _Default : System.Web.UI.Page
   6:     {
   7:         protected void EventControl1_ButtonClicked(object sender, EventArgs e)
   8:         {
   9:             MessageLabel.Text = "You clicked it! " + DateTime.Now.ToLongTimeString();
  10:         }
  11:     }
  12: }

You can see in Default.aspx that intellisense of our user control contains our new event. Note that the event is called On<Event name> when it is used in markup, if you look in the code behind you can see that the event really is called ButtonClicked.

We create an event handler for the event and perform some action, updating a label with a message and the time so we see that something has happened.

You can recreate the sample or download the attached .zip-file containing a complete solution. This was a real quick example, next time I’ll extend this concept and show how to send data along with the event.

UserControl Event 1.zip (18,09 kb)

Comments (11) -

Why i don't see your attached .zip-file???

Reply

How to pass values from User Control to Page or calling Page methods from User Control.

interviews.dotnetthread.com/.../...control-to.html

Reply

It's really very helpful. Thanks for this article.

Reply

For some reasone the .zip file had disappeared. I've re-uploaded it now so you can grab the sample code.

Reply

Thanks for re-uploaded the .zip file.

Reply

Ukraine DrMegavolt

It is very cool, but if button1 is created dynamically Button Button1 = new Button{Text="btn" ...}; Button1.Click+=new EventHandler(ClickButton_Click); then  events not fired  (

Reply

This article does not make sense. Why not to use OnBubbleEvent but invent unnecessary new events?

Reply

alex> It's nice to expose your events with names that makes sense for the domain that the user control contains. You should check out part 2 of the article where I create a "Person created"-event that passes the created person (user) along with the event args. That makes way more sense for the end user of the control than listening for a bubbeling event from a button.

OnBubbleEvent works fine for simple scenarios, but even then I like to name the event so that the name itself tells me what has happened.

Reply

Great info, mats - keep up the good work.

Reply

After reading the article, I feel that I need more information on the topic. Can you suggest some resources please?, Excellent post!

Reply

Add comment