How to add an onClick event to a Label in asp.net

Add an onClick event to a Label
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can add an onClick event to a Label web server control. But there is no built-in onClick event in the Label control. So we have to find an alternate solution to attach a click event to a Label control.

In the below asp.net c# code, we used the Label control’s Attributes property to add a click event to a Label web server control. The Attributes property allows us to add a javascript click event to a Label server control.

The Label Attributes property gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control. This property is inherited from WebControl. The Attributes property value is an AttributeCollection of name and value pairs.

So finally, using this Attributes property the asp.net developers can add a javascript onClick event to the Label control. In this example code, we showed an alert on the web browser when someone clicks the Label control.
test.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        Label1.Attributes.Add("OnClick", "javascript:alert('label clicked.')");
    }    
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>asp.net example - label onclick</title>      
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label onclick
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Font-Size="XX-Large"
            Text="Click Here To Test Label OnClick Event."    
            >      
        </asp:Label>      
    </div>      
    </form>      
</body>      
</html>