ASP.NET LinkButton Control: Combining Hyperlink Appearance with Server-Side Functionality

Learn how to use the ASP.NET LinkButton control to create interactive hyperlinks that trigger server-side events. This tutorial explains its implementation, demonstrates handling click events in the code-behind, and highlights its advantages over standard HTML hyperlinks for building dynamic web applications.



ASP.NET LinkButton Control

What is a LinkButton?

The LinkButton control in ASP.NET is a server-side control that looks and acts like a hyperlink but functions as a button. This means it can trigger server-side events when clicked, unlike a standard HTML hyperlink.

LinkButton Syntax

You create a LinkButton control using the following ASP.NET syntax within your .aspx page:

Code

<asp:LinkButton ID="LinkButton1" runat="server" Text="Click Me" OnClick="LinkButton1_Click" />

This creates a LinkButton with the text "Click Me". The `OnClick` attribute specifies the server-side method to call when the button is clicked.

Example: LinkButton with Event

This example shows a LinkButton that, when clicked, updates a Label control on the page.

LinkButtonExample.aspx (ASPX):

Code

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

<asp:LinkButton ID="LinkButton1" runat="server" Text="Click Me" OnClick="LinkButton1_Click" /><br />
<asp:Label ID="Label1" runat="server" />

LinkButtonExample.aspx.cs (Code-Behind):

Code

using System.Web.UI.WebControls;

namespace LinkButtonExample
{
    public partial class LinkButtonExample : System.Web.UI.Page
    {
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Label1.Text = "Button Clicked!";
        }
    }
}

When the button is clicked, the `LinkButton1_Click` method in the code-behind file is executed, updating the Label with a message.