2

I am loading a string from my database which among other things contains line breaks (\r\n). However, this isn't being rendered as a new line but instead as \r\n.

If I type it directly in instead of loading it from a string, it works just fine but I need to be able to load it from a string.

Any ideas?

Edit: Upon closer inspection, it looks like the string is being returned as:

Changed test7\\r\\nChanged test8\\r\\nChanged test9Changed test7

From the database.

I tried running a .Replace(@"\\", @"\") on it but this had no effect at all. Any ideas?

5 Answers 5

5

What about this?

string yourString="something\r\n..somethingMore";
yourString=yourString.replace("\r\n",Environment.NewLine);
yourTextBox.Text=yourString;

Does this solution meet your requirements?

2
  • Thx for formatting my answer @competent_tech, still getting used to it :) Commented Apr 1, 2012 at 22:54
  • Silly me! I forgot to quote the string to be replaced, this should work yourString=yourString.replace(@"\r\n",Environment.NewLine); Thanks for pointing it out to me mate :) Commented Apr 2, 2012 at 20:19
2

Call .Replace(@"\r", "\r").Replace(@"\n", "\n")

or just .Replace(@"\r\n", "\r\n")

1

This won't work .Replace("\\", "\") because it sees the backslash as an escape, but strangely, this doesn't work when it should: .Replace(@"\\", @"\")

The one that I got to work is this:

.Replace("\\r\\n", "\r\n");
1
  • I still don't understand how it works, but it does. Shouldn't \\r\\n translate to \r\n? Commented Apr 2, 2012 at 10:13
1

Is the Multiline property on your TextBox set to true?

1

When you call your .Replace function, you're appending your strings with @. By doing so, your @"\\" gets converted to "\\\\" and your @"\" gets converted to "\\".

Try running .Replace("\\", "\"), and it should work.

1
  • That doesn't work because the `` gets countes as an escape character. Commented Apr 2, 2012 at 10:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.