How to create a URL enable Label or Text in ASP.Net with C# - ASP TANMOY

Latest

Tuesday, 24 December 2013

How to create a URL enable Label or Text in ASP.Net with C#


Description:
 Sometimes we need to show text to a webpage. If there is any URL link to text then this link to be shown as URL Link like the image bellow. There is simple regular expression which helps to detect the url from the
text.



 

Step1:
Open Visual Studio first. Then create an empty web page.
Step2:
Take a label from toolbox to show text.



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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body bgcolor="#cccccc">
    <form id="form1" runat="server">
    <div>
    </div>
    <p>
        <asp:Label ID="Label1" runat="server" Text="" style="top: 153px; left: 440px;  height: 19px;  position: absolute;"></asp:Label>
    </p>
    </form>
</body>
</html>



Step3:

Add two Namespace

11. using System.Text;

22. using System.Text.RegularExpressions;





Step4:

Create a function and add the following code.
 


private void urlLink()
    {
        Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
       

        MatchCollection mactches = regx.Matches(Label1.Text);
       
        foreach (Match match in mactches)
        {
            Label1.Text = Label1.Text.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
        }

       

    }




Step5:
protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "Hi.This is the article for URL Dectection. This is UrL:http://www.campusmoo.co.in ";
        urlLink();
    }





 
Add this function to the page load event

Step6:
Run the project and Enjoy.



 

1 comment: