Events in UserControls
First, we create a new, simple EventUserControl, with this code in it:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EventUserControl.ascx.cs" Inherits="EventUserControl" %> Page title: <asp:TextBox runat="server" ID="txtPageTitle" /> <asp:Button runat="server" ID="btnUpdatePageTitle" OnClick="btnUpdatePageTitle_Click" Text="Update" />All just text and server controls that we know. In the CodeBehind, it looks a bit like this:
public partial class EventUserControl : System.Web.UI.UserControl { private string pageTitle; public event EventHandler PageTitleUpdated; protected void btnUpdatePageTitle_Click(object sender, EventArgs e) { this.pageTitle = txtPageTitle.Text; if(PageTitleUpdated != null) PageTitleUpdated(this, EventArgs.Empty); } public string PageTitle { get { return pageTitle; } } }We have defined a pageTitle container variable and a property for it. Then we have a new thing, an event. As you can see, it's defined much like any other kind of field, but it is a bit different. The theory about is explained in the C# tutorial, so we won't get into that here. In the Click event of our button, we set the pageTitle field. Then we check if PageTitleUpdated, our event, is null. If it's not, it means that we have subscribed to this event somewhere, and in that case, we send a notification by calling the PageTitleUpdated as a method. As parameters, we send this (a reference to the UserControl it self) as the sender, and an empty EventArgs parameter. This will make sure that all subscribers are notified that the pageTitle has just been updated. Now, in our page, I've declared our UserControl like this:
<%@ Register TagPrefix="My" TagName="EventUserControl" Src="~/EventUserControl.ascx" %>And inserted it like this:
<My:EventUserControl runat="server" ID="MyEventUserControl" OnPageTitleUpdated="MyEventUserControl_PageTitleUpdated" />As you can see, we have defined an event handler for the PageTitleUpdated event like if it was any other server control. In the CodeBehind of our page, we define the simple event handler for the UserControl event like this:
protected void MyEventUserControl_PageTitleUpdated(object sender, EventArgs e) { this.Title = MyEventUserControl.PageTitle; }It's that simple! Now obviously, updating the page title could have been done directly from our UserControl, so it's just to provide a simple example on how to use events, but as you will likely learn later on, this technic will come in handy in lots of situations.
Having problems with this chapter? Ask in our forums!
Could this article help your friends? Please help us to help them by sharing it on Facebook or Twitter: