Click to See Complete Forum and Search --> : How to add a newline with in a string being set to a label [C# 2005]


Shaitan00
August 10th, 2008, 02:45 AM
I am trying to find a way to introduce a NEW LINE into a string I am setting for the text of a label, specifically I want the label to span 3 lines... I've tried using "\n" but it doesn't seem to work at all, this is my current code...


lblAddress.Text = province.ToString() + " - " + city.ToString() + " - " + address.ToString() + " - " + postal_code.ToString();


What I want to do is set the ADDRESS on another line and the POSTAL_CODE on another line so that the text of the label spans 3 lines, something like the following:
Ontario Toronto
123 Mission Street
D4C 4D4


lblAddress.Text = province.ToString() + " - " + city.ToString() + "\n" + address.ToString() + "\n" + postal_code.ToString();


But this doesn't work ... any clue why?
This is to be used with an ASP:LABEL in ASP.NET 2.0 (not a form label) - incase this makes any difference...

Any help would be greatly appreciated...
Thanks,

darwen
August 10th, 2008, 04:34 AM
Newlines in Windows are "\r\n" and this is contained in System.Environment.NewLine e.g.


lblAddress.Text =
province.ToString() + " - " + city.ToString() + Environment.NewLine +
address.ToString() + Environment.NewLine +
postal_code.ToString();


But if 'province', 'city', 'address' and 'postal_code' are strings you don't need the 'ToString'

i.e.


lblAddress.Text =
province+ " - " + city + Environment.NewLine +
address + Environment.NewLine +
postal_code;


There are a lot of temporary strings being created in the above line, so it would be better to use a string builder :


System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
stringBuilder.Append(province);
stringBuilder.Append(" - ");
stringBuilder.AppendLine(city);
stringBuilder.AppendLine(address);
stringBuilder.AppendLine(postal_code);

lblAddress.Text = stringBuilder.ToString();


Darwen.