Newline character literal in ASP.Net (C# & VB.Net)

Mohammed Imtiyaz Feb 25, 2015

Sometime we come across the scenarios where we need to break the string in the middle. In this tutorial you will learn how to do this.

Suppose you have a string in your page load event as follows:

C#

protected void Page_Load(object sender, EventArgs e)
{
    string strText = "First line Second line Third line Fourth line";
    Response.Write(strText);
}

VB.Net

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Dim strText As String = "First line Second line Third line Fourth line"
    Response.Write(strText)
End Sub

When you run this code, the output will be as follows:

First line Second line Third line Fourth line

Assume that you want to break this string at some specific length. You can do it by simply modifying the above code as follows:

Add New Line Literal "\n" and Carriage Return Literal "\r" at the point where you want to break the string and replace those literals with breakline "<br />"

C#

protected void Page_Load(object sender, EventArgs e)
{
    string strText = "First line\r\n Second line\r\n Third line\r\n Fourth line";
    strText = strText.Replace("\r\n", "<br />").Replace("\r", "<br />") ;
    Response.Write(strText);
}

VB.Net

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Dim strText As String = "First line\n\r Second line\n\r Third line\n\r Fourth line"
    strText = strText.Replace("\n\r", "<br />").Replace("\r", "<br />")
    Response.Write(strText)
End Sub

When you run this code, the output will be as follows:

First line
Second line
Third line
Fourth line