Mats Lycken development

.NET and web related blog posts

NAVIGATION - SEARCH

ASP.NET 101 - Part 2: Sending event data in your custom events

One of the key benefits of encapsulating logic and behavior in a user control is that the user of the control doesn’t have to care about the inner workings of the control. We only need to expose the things that the users of the control needs.

We will demonstrate this by creating a simple user registration control. The control will expose an event, UserCreated, which will contain the newly created user as data.

This way the page that the user control is located in doesn’t need to care about what fields the user needs to fill out or how the person is created. It is simply handed a user that was created.

We’ll start by looking at our sample user control.

PersonEntryControl.ascx

   1: <%@ Control Language="C#" AutoEventWireup="true" 
   2: CodeBehind="PersonEntryControl.ascx.cs" Inherits="PersonEntryControl" %>
   3: First name: <br />
   4: <asp:TextBox runat="server" ID="FirstNameTextBox" /> <br />
   5: Last name: <br />
   6: <asp:TextBox runat="server" ID="LastNameTextBox" /> <br />
   7: Email: <br />
   8: <asp:TextBox runat="server" ID="EmailTextBox" /> <br />
   9: <asp:Button runat="server" ID="AddButton" Text="Add" 
  10:     onclick="AddButton_Click" />

PersonEntryControl.ascx.cs

   1: using System;
   2: namespace UserControl_Event_2
   3: {
   4:     public partial class PersonEntryControl : System.Web.UI.UserControl
   5:     {
   6:         protected void AddButton_Click(object sender, EventArgs e)
   7:         {
   8:             Person newPerson = new Person()
   9:             {
  10:                 FirstName = FirstNameTextBox.Text,
  11:                 LastName = LastNameTextBox.Text,
  12:                 Email = EmailTextBox.Text
  13:             };
  14:             OnPersonCreated(new GenericEventArgs<Person>(newPerson));
  15:         }
  16:         public event EventHandler<GenericEventArgs<Person>> PersonCreated;
  17:         protected void OnPersonCreated(GenericEventArgs<Person> e)
  18:         {
  19:             if (PersonCreated != null)
  20:             {
  21:                 PersonCreated(this, e);
  22:             }
  23:         }
  24:     }
  25: }

As you can see the user control contains a button and three textboxes for first name, last name and email address.

When we click the button we create a new person and then trigger the event. If you look at the event declaration you can see that it differs from the previous example.

public event EventHandler<GenericEventArgs<Person>> PersonCreated;

 

We are now using a generic version of the EventHandler that allows us to specify what type the EventArgs parameter should be. Here I have created a generic EventArgs class that allows us to send any data structure along with our event.

Here is what the GenericEventArgs<T> class looks like:

GenericEventArgs.cs

   1: using System;
   2:  namespace UserControl_Event_2
   3: {
   4:     public class GenericEventArgs<T> : EventArgs
   5:     {
   6:         public T Data { get; set; }
   7:         public GenericEventArgs(T data)
   8:         {
   9:             Data = data;
  10:         }
  11:     }
  12: }

The most important thing about it is that it inherits from EventArgs, this is what allows us to use it with our event.

Now when we trigger the event from the user control we can send along the created person with the line:

OnPersonCreated(new GenericEventArgs<Person>(newPerson));

 

Now let’s create a page where we can try out the user control.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
 Inherits="UserControl_Event_2._Default" %>
<%@ Register src="PersonEntryControl.ascx" tagname="PersonEntryControl" 
tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        <uc1:PersonEntryControl ID="PersonEntryControl1" runat="server"
              OnPersonCreated="PersonEntryControl1_PersonCreated" />    
    </div>
    <div>
        <asp:Label runat="server" ID="StatusLabel" />
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
namespace UserControl_Event_2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void PersonEntryControl1_PersonCreated(object sender, 
                            GenericEventArgs<Person> e)
        {
            StatusLabel.Text = string.Format("Created person: {0} {1}",
                e.Data.FirstName, e.Data.LastName);
        }
    }
}

As you can see in the event handler we can easily access the person with e.Data.

Download the sample and play around with it, a nice exercise is to add some validation to the user control and maybe add some more fields to the person.

UserControl Event 2.zip (21,22 kb)

Comments (1) -

Nice to see that your blog is coming back to life. Looking forward to your next post!

Reply

Add comment