.Net ramblings
# Sunday, 03 October 2004
Complications with textbox and Newline and Carriage Return characters

My windows application uses a multi-line textbox to allow the user to update text, which gets sent to and from a web service, and then into and out of a sql database.  Somewhere along the way, the \r\n characters turn into \n characters.  So when i re-load the string from the web service into the textbox, it gets displayed as block characters instead of proper line breaks.  I wrote the following simple function to work around this issue. 

It firstly removes all the \r characters, which has the effect of changing the \r\n characters to \n. Then it replaces the \n chars to \r\n. 

Note: The reason you can't just replace the \n chars with \r\n is because you would end up with \r\r\n chars if there were \r\n's in the string before you did the replace.

/// 
/// this method formats a string for correct display in a multiline text box.
/// It removes \n characters and replaces them with correct \r\n chars
/// 
public static string FormatForMultiLineTextBox(string s)
{
return s.Replace("\r","").Replace("\n","\r\n");
}

i will also take this opportunity to share a method i use to prevent errors caused by sending certain binary characters across a web service (at least in WSE 2).  The method removes all un-useful binary characters (useful... in terms of my app).

/// 
/// This method removes all binary characters except:
/// Vertical Tab 0x09
/// New Line 0x0A
/// Carraiage Return 0x0D
/// 
public static string StripBinaryChars(string s)
{
    return Regex.Replace(s, @"[\x00-\x08\x0B-\x0C\x0E-\x1F]","");
}

see www.asciitable.com for more information on the hex codes for these binary characters.


Sunday, 03 October 2004 18:40:37 (GMT Daylight Time, UTC+01:00)  #    Comments [0]  .Net Windows Forms

OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview