Converting SQL Server newline character to HTML break <br/>
A common scenario (at least for me) is the following:
1. Accept text input into a web form that includes multiline text boxes. The text often includes line breaks.
2. The text is stored in a database such as SQL Server 2005. SQL Server 2005 has no problem storing the line breaks.
3. I then display the data in an ASP.NET gridview control. Because the control renders as HTML, it doesn’t recognize the newline escape characters.
The problem is how to convert the newline characters into <br />. Here is one solution. It is closely based on this MSDN article: http://msdn2.microsoft.com/en-us/library/xwewhkd1.aspx (regex.replace)
This C# example assumes you are using an ASP.NET FormView with a label called lblSampleText:
//Create a regular expression that matches a newline
string pattern = "\n";
Regex rgx = new Regex(pattern);
//Find the relevant label from the FormView
Label vL1 = checked((Label)FormView1.FindControl("lblSampleText"));
string inputStr = vL1.Text;
//Replace the newline character with br
string outputStr = rgx.Replace(inputStr,"<br/>");
// Display the resulting string
vL1.Text = outputStr;
This VB example assumes you are using a GridView with a TemplateField control. Inside the TemplateField control (ItemTemplate) is a label called lblSampleText.
Protected Sub GridView3_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView3.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
' Create a regular expression that matches a newline
Dim pattern As String = "\n"
Dim rgx As New Regex(pattern)
' Find the relevant label from the gridview
Dim inputStr As String = CType(e.Row.FindControl("lblSampleText"), Label).Text
' Replace the newline character with <br/>
Dim outputStr As String = rgx.Replace (inputStr, "<br/>")
' Display the resulting string.
CType(e.Row.FindControl("lblSampleText"), Label).Text = outputStr
End If
End Sub
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Good post. While building a commenting feature for a website I’m working on, I needed to convert “\n” to as well.
I found another way to do this.
Here’s what I did – it is in C#:
I am using a repeater control which displays the comments.
In my page class, I created a RegEx variable like so:
protected static Regex regEx = new Regex(“\n”);
protected void Page_Load(object sender, EventArgs e)
{
…
}
Then, within my repeater control’s section, I included this:
<%# regEx.Replace((string)DataBinder.Eval(Container.DataItem, "body"), "”) %>
“body” is the column name returned by my database procedure for the comment text.
Both ways seem to work fine.
My way has less code, though.
Thanks for the post!