ASP.NET Hosting

Events and Delegates in ASP.NET Web Forms

Nearly every server control in ASP.NET Web Forms, including Button, is based on the idea of delegates and events. Select DropDownList. TextBox or SelectedIndexChanged. Text was altered. These are pre-installed events that cause particular server methods (event handlers) to be triggered. To keep your code modular and reusable, you can also use delegates to build your own unique events.

2. What Are Delegates and Events?

Concept Description
Delegate A reference type that defines the signature of a method. Think of it as a “function pointer” with safety.
Event A notification mechanism that signals subscribers when something happens. Built on top of delegates.

Real-Time Scenario

Use Case

You have an Order Processing System.

When an order is placed:

  • A Business Logic class (OrderManager) processes the order.
  • It raises an event when the order is completed.
  • The WebForm (UI) listens to that event and updates the user (like “Order Confirmed Successfully”).

This helps separate business logic from UI logic.

3. Step-by-Step Implementation

Folder Structure

/App_Code
    └── OrderManager.cs
/OrderPage.aspx
/OrderPage.aspx.cs

Step 1: Create Delegate and Event in App_Code/OrderManager.cs

using System;

public delegate void OrderProcessedHandler(string message);

public class OrderManager
{
    // Declare event
    public event OrderProcessedHandler OrderProcessed;

    // Method to process the order
    public void ProcessOrder(string orderId)
    {
        // Simulate processing logic
        System.Threading.Thread.Sleep(2000);

        // Raise event after processing
        OnOrderProcessed($"Order #{orderId} has been successfully processed!");
    }

    // Method to raise the event
    protected virtual void OnOrderProcessed(string message)
    {
        if (OrderProcessed != null)
        {
            OrderProcessed(message); // Trigger the event
        }
    }
}

Step 2: Design the Web Form (OrderPage.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OrderPage.aspx.cs" Inherits="OrderPage" %>

<!DOCTYPE html>
<html>
<head>
    <title>Order Processing with Delegates and Events</title>
</head>
<body>
    <form id="form1" runat="server">
        <div style="width:400px; margin:auto; text-align:center; font-family:Arial;">
            <h2>🛒 Order Processing System</h2>

            <asp:Label ID="lblOrderId" runat="server" Text="Enter Order ID:"></asp:Label><br />
            <asp:TextBox ID="txtOrderId" runat="server" Width="200px"></asp:TextBox><br /><br />

            <asp:Button ID="btnProcess" runat="server" Text="Process Order" OnClick="btnProcess_Click" /><br /><br />

            <asp:Label ID="lblStatus" runat="server" Text="" ForeColor="Green" Font-Bold="True"></asp:Label>
        </div>
    </form>
</body>
</html>

Step 3: Code Behind (OrderPage.aspx.cs)

using System;

public partial class OrderPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Nothing special on load
    }

    protected void btnProcess_Click(object sender, EventArgs e)
    {
        string orderId = txtOrderId.Text.Trim();

        if (string.IsNullOrEmpty(orderId))
        {
            lblStatus.Text = " Please enter a valid Order ID!";
            return;
        }

        // Create an object of OrderManager
        OrderManager orderManager = new OrderManager();

        // Subscribe to the event
        orderManager.OrderProcessed += ShowOrderStatus;

        // Start processing
        lblStatus.Text = "Processing your order...";
        orderManager.ProcessOrder(orderId);
    }

    // Event handler method
    private void ShowOrderStatus(string message)
    {
        lblStatus.Text = message;
    }
}

4. How It Works

  1. User enters Order ID and clicks “Process Order”.
  2. OrderManager class runs the business logic in the backend.
  3. When done, it raises an event OrderProcessed.
  4. The OrderPage (UI layer) subscribes to that event and executes ShowOrderStatus() to display confirmation.

Output Example

Before Processing:

“Processing your order…”

After 2 seconds:

“Order #1234 has been successfully processed!”

5. Explanation

Part Description
OrderProcessedHandler Delegate defining the method signature
OrderProcessed Event raised after order completion
ProcessOrder() Simulates real-time order processing
ShowOrderStatus() UI method that responds when event is fired
+= Subscribes the event handler
OnOrderProcessed() Safely raises the event

6. Real-Time Use Cases in Web Applications

Scenario Delegate/Event Purpose
Order Processing System Notify UI when order is completed
Payment Gateway Integration Raise event after successful payment
Email/SMS Notification Service Trigger event when message sent
Data Import Task Update progress status
Stock Market Dashboard Notify UI when stock price changes
Background Report Generation Fire event when report ready

7. Behind the Scenes in ASP.NET Controls

ASP.NET controls internally use events heavily:

  • Button.Click → Built-in delegate event
  • TextBox.TextChanged
  • DropDownList.SelectedIndexChanged

When you write:

btnSubmit.Click += BtnSubmit_Click;

You are literally subscribing to a delegate-based event defined in Button control.

8. Advantages

  • Loose Coupling: UI doesn’t depend on how business logic works.
  • Reusability: Same event can be reused in multiple pages.
  • Maintainability: Easy to update backend logic without touching UI.
  • Scalability: Ideal for background processing tasks and async workflows.

9. Conclusion

Delegates and Events are not limited to desktop apps — they are fundamental in ASP.NET Web Forms too.
By applying them in real-time web projects, you can build modular, event-driven, and scalable systems that respond dynamically to backend processes.

ASP.NET Core 10.0 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.