6

I have a windows phone application. In the application I have a textbox whose acceptsreturn property is set to true.

What I want to do is create a string from the textbox and replace the new lines with a specific character, something like "NL"

I've tried the following but none of them worked.

string myString = myTextBox.Text.Replace(Environment.NewLine,"NL");
string myString = myTextBox.Text.Replace("\n","NL");
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
user1924391
  • 255
  • 5
  • 13
  • 1
    Are you sure it's the newline character you are after, and not `carriage return` - \r? Does `string myString = myTextBox.Text.Replace("\r","NL");` work? Environment.NewLine is usually `\r\n` on Windows for example, so you've tried \n and \r\n! – dash Mar 05 '13 at 10:06
  • Why didn't it work? Was there an exception? Or was the output not formatted as you wanted? – psubsee2003 Mar 05 '13 at 10:07
  • well it didnt cause an exception, it just didnt work. newline didnt get replaced – user1924391 Mar 05 '13 at 10:08
  • string myString = myTextBox.Text.Replace("\r","NL"); worked! Thank you a lot, ive been searching for this the whole morning. I had no idea that the carriage return \r existed! – user1924391 Mar 05 '13 at 10:10

4 Answers4

7

I'm not familiar with windows phone(or silverlight), but try to split with \r instead:

string myString = myTextBox.Text.Replace("\r","NL");

Why does a Silverlight TextBox use \r for a newline instead of Environment.Newline (\r\n)?

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Consider replacing different types of line breaks to handle all the possibilities

string myString myTextBox.Replace("\r\n", "NL").Replace("\n", "NL").Replace("\r", "NL");
Raab
  • 34,778
  • 4
  • 50
  • 65
1

Use this code

var myString = myTextBox.Text.Replace("\r","NL");

This is for compatibility with every operating systems.

0

A question with a similar topic had a quite elegant answer you might consider interesting to use:

using System.Text.RegularExpressions;

myTextBox.Text = Regex.Replace(myTextBox.Text, @"\r(?!\n)|(?<!\r)\n", "NL");
Community
  • 1
  • 1
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78