Displaying the text that was originally stored using multi line TextBox

One common problem that face the developers is that when they store a text using Multiline text box ,and try to dispaly that text using the label ( or any other control) on the form, they will find that the line breaks and spaces is not being rendered with in the text.

This is because the line break character in text box text is the .NET newline character which is “\n” or Envirnment.NewLine,and the same for the space which is “\t”.And since the browsers can’t understand those characters,they will not displayed in the rendered text. hence the rendered text will look messy.

One simple solution is to replace those characters with there equivalent html tags that can be understood by the browsers.

So the “\n” can be replaced by “<br/>” and the “\t” with “&nbsp;&nbsp;&nbsp;”  ( three space characters in html).

The .NET code for this could be :

  string OrginalTextFromDataBase=TextBox1.Text;        
  Label1.Text = OrginalTextFromDataBase.Replace("\n", "<br/>").Replace("\t","&nbsp;&nbsp;&nbsp;");

So, you don’t have to worry about the stored text , just format it correctly when you want to dispaly it as html.

Note:If you want to dispaly the text in the textbox for further editing , then there is no need to replace those characters because the textbox control will recognize them.

Anas Ghanem

2 Comments

Comments have been disabled for this content.