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

January 19, 2009 12:13 by MatsLycken

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)


Currently rated 4.5 by 6 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

January 20. 2009 05:16

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

Robert

March 23. 2009 11:47

Pingback from esersahin.wordpress.com

ASP.NET 101 – Part 2: Sending event data in your custom events « using …

esersahin.wordpress.com

May 15. 2009 06:19

thanks for this usefull informations ..
now i find what i want to know, thanks ..

graphics comments

October 29. 2009 03:42

i like

ed hardy shoes

December 3. 2009 14:49

thanks for this usefull informations ..

Cheap auto insurance quotes

December 6. 2009 02:10

Hello admin, thnx for providing this information..., i found it incredible. Take care, John Black..

son moda

December 12. 2009 00:49

Greetings everyone, This site is good quality and so is how the matter was expanded. I like some of the comments as well although I would prefer we focus on the topic in order add value to the topic. It will be also encouraging to the one who penned it down if we all could mention it (for those who have social accounts such as a reddit, facebook,..). Again, Thanks..

pure acai berry

December 18. 2009 13:44

I’m really very useful to follow a long-time see this as a blog here Thank you for your valuable information.

casino gratuit

December 18. 2009 22:39

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

Kids Thanksgiving Recipes

December 19. 2009 15:17

Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

freelancers

December 21. 2009 04:03

Easily, the article is in reality the greatest on this worthy topic. I harmonize with your conclusions and will eagerly look forward to your future updates. Just saying thanks will not just be enough, for the tremendous clarity in your writing. I will immediately grab your rss feed to stay privy of any updates. Gratifying work and much success in your business endeavors!

baisez

December 21. 2009 14:32

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

us online casinos

December 22. 2009 01:24

This has certainly gives me some ideas to shape up. Thank you

Keith Peterson

December 23. 2009 09:27

I don’t usually reply to posts but I will in this case. WoW Smile

Roger Zacher

December 23. 2009 11:03

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

advertising chiropractic

December 23. 2009 21:50

That’s nice to finally find a website where the blogger is very knowledgable.

Hannah

December 24. 2009 12:24

I personally have embraced the new technologies and the CMS platforms, I think the new tools only make the web designs better. I am glad that new technologies are coming out in web design that make things easier, improved, and better looking for design.

meilleur assurance hypothecaire

December 24. 2009 16:48

Merry xmas and happy new year to all of you.

articles

December 26. 2009 14:13

good!

exchange rate widget

December 26. 2009 14:14

I like it@!

exchange rate widget

December 26. 2009 14:14

nice !

currency converter widget

December 26. 2009 14:15

thanks!

currency converter widget

October 28. 2011 14:04

Pingback from fashionmagazines.oclipa-moldova.com

PFT: Dolphins sign Losman as backup | Fashion Magazines

fashionmagazines.oclipa-moldova.com

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

February 7. 2012 01:20