How to encode html in a Label in asp.net

asp.net example - label encode html
Label is an asp.net web server control. mainly label control is used to display formatted text in web page. label Text property allow us to specify text to display in web page. label server control can render some html code when displaying text in web page such as bold, italic, anchor etc.

in this example we displayed html tag in a label control as text. to do this we take help from server.HtmlEncode() method. HtmlEncode method applies html encoding to a specified string. so HtmlEncode() method allow us to encode some special characters to their HTML-encoded equivalent before render the label text in web browser. finally label control display html tags in web page.

the following asp.net c# example code demonstrate us how can we display html inside a label control in an asp.net application.
label-encode-html.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  
    
<!DOCTYPE html>
      
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.Text = Server.HtmlEncode("<h3>This is a heading</h3>");
        Label1.Text += "<br />";
        Label1.Text += Server.HtmlEncode("<p>This is a paragraph.</p>");
        Label1.Text += "<br />";
        Label1.Text += Server.HtmlEncode("<button type='button'>Click Me!</button>");
        Label1.Text += "<br />";
        Label1.Text += Server.HtmlEncode("<meta name='author' content='innee'>");
    }  
</script>      
      
<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>asp.net example - label encode html</title>
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label encode html
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="sample label to display html code."
            Font-Size="X-Large"
            >      
        </asp:Label>      
        <br /><br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="label encode html"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>      
    </form>      
</body>      
</html>
More asp.net examples