ASP.NET Raising Events

In the ASP.NET applications that I write, the ASP.NET User Controls (System.Web.UI.UserControl) contain the UI controls that interact direcly with the user.  The User Controls do not retrieve data but rather process user events - raise events.

The ASPX pages (System.Web.UI.Page) rarely contain UI controls but contain the User Controls. They are responsible for retrieving application data and sending the data to the User Controls.

Giving the user controls sole responsibility of user interaction helps me to keep my code and applications organized.

In the example below, the ASPX page contains a button that submits a calculation to the code behind classes.

///////////////////////////////////////////////////////////////////////////
ASPX listens & initializes User Control
///////////////////////////////////////////////////////////////////////////
In PageLoad method I add:

//initialize user control
UCCalculate.Initialize();
//register event listener with user control            
UCCalculate.ClickedCalculateButton += new EventHandler(EventListener);

Somewhere in the ASPX page add the method that is called when the user control raises an event.

public void EventListener(object sender, EventArgs e)
{
 if (sender is Button)
 {
   //process button action here
 }
}

//////////////////////////////////////////////////////
User Control raises events
///////////////////////////////////////////////////////

Declarations section:

public event EventHandler ClickedCalculateButton;

on click of button call Click_Calculate method.

<asp:Button id="btnSubmit" runat="server" 
                  Text="Calculate" 
                  OnClick="Click_Calculate" 
                  CommandName="Calculate" 
                  CssClass="button"/>

Somewhere in the User Control class:

public void Click_Calculate(object sender, EventArgs e)
{
 //check if listener was registered
 if (ClickedCalculateButton != null)
 {
  //raise event (goes to ASPX EventListener method mentioned above) to process button action
  ClickedCalculateButton(Btn_clicked, e);
 }
}

I finally documented my madness. I hope this helps you, too. How do you handle events in your ASP.NET application?

Signing Off,
Vivian
ViSO Tech

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name (required)

 Email (will not be published) (required)

Your comment is 0 characters limited to 3000 characters.