December 2006 - Posts

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 my solution. It is closely based on this MSDN article: http://msdn2.microsoft.com/en-us/library/xwewhkd1.aspx (regex.replace)

The 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