CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2004
    Posts
    429

    Question How to add a newline with in a string being set to a label [C# 2005]

    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...

    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

    Code:
    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,

  2. #2
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: How to add a newline with in a string being set to a label [C# 2005]

    Newlines in Windows are "\r\n" and this is contained in System.Environment.NewLine e.g.

    Code:
    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.

    Code:
    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 :

    Code:
    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.
    Last edited by darwen; August 10th, 2008 at 04:37 AM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured