ASP.NET WebForms uses an event-driven programming model, similar to Windows applications.
When a user interacts with a control (like clicking a button), an event is triggered and ASP.NET executes the associated server-side code.
In this article, we will learn:
What does event handling mean in WebForms
How button click events work
Real-time business example
Page life cycle flow of button click
What is Event Handling in ASP.NET WebForms?
Event handling refers to the process by which user actions (events) trigger server-side methods.
Common WebForms events
| Control | Event |
|---|
| Button | OnClick |
| TextBox | TextChanged |
| Dropdown | SelectedIndexChanged |
| GridView | RowCommand |
WebForms automatically generates postback to the server and executes the event handler.
Button Click Event Example
ASPX (UI Design)
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
C# Code-behind (Event Handler)
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblMessage.Text = "Hello, " + txtName.Text + "! Welcome to ASP.NET WebForms.";
}
How does it work?
User enters a name in the TextBox.
User clicks the Submit button
Page sends a PostBack request to the server
The event handler executes
Server returns a response with updated Label text
Real-Time Business Example
Scenario: Employee Login Page
ASPX
<asp:TextBox ID="txtEmpId" runat="server"></asp:TextBox>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
<asp:Label ID="lblStatus" runat="server"></asp:Label>
C# Code
protected void btnLogin_Click(object sender, EventArgs e)
{
if(txtEmpId.Text == "EMP001" && txtPassword.Text == "admin123")
{
lblStatus.Text = "Login Successful!";
lblStatus.ForeColor = System.Drawing.Color.Green;
// Redirect to dashboard: Response.Redirect("Dashboard.aspx");
}
else
{
lblStatus.Text = "Invalid Employee ID or Password";
lblStatus.ForeColor = System.Drawing.Color.Red;
}
}
PostBack & ViewState Role
| Feature | Purpose |
|---|
| PostBack | Sends request back to server |
| ViewState | Maintains control values between requests |
So after clicking the button, the page reloads but the values remain intact.
Behind the Scenes Event Sequence
Button click triggers this life cycle:
Page Load
PostBack event handling
Button Click Event fired
Render Page
Response sent to browser
Conclusion
Event handling in WebForms enables:
Server-side execution of user actions
Easy programming model (Windows Forms style)
Automatic ViewState + PostBack support
Button click is one of the most commonly used events to perform tasks like:
Login validation
Form submission
Calculation (e.g., tax, salary)
Search filters
Saving data to the database