5

In C I use "1st line 1\n2nd line" for a newline, but what about VB? I know "1st line" & VbCrLf & "2nd line" but its too verbose, what is the escape char for a newline in VB?

I want to print

1st line
2nd line

I tried using \n but it always outputs this no matter how many times I run the compiler

1st line\n2nd line

Any ideas?

  • You can also use `myStr = myStr.Replace("\n", Environment.NewLine)` where myStr already contain your content incl. \n. Works well as a custom extension too. –  Dec 28 '12 at 22:53

5 Answers5

8

You should use Environment.NewLine. That evaluates to CR+LF on Windows, and LF on Unix systems.

There are no escape sequences for CR or LF characters in VB. And that's why "\n" is treated literally. So, Environment.NewLine is your guy.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
3

As others have said, you should be using the environment-sensitive Environment.NewLine property. vbCrLf is an old VB6 constant which is provided in VB.NET for backwards compatability. So for instance, you should be using:

"1st line" & Environment.NewLine & "2nd line"

If that's too wordy when you have many lines, you can use the StringBuilder class, instead:

Dim builder As New StringBuilder()
builder.AppendLine("line 1")
builder.AppendLine("line 2")
builder.AppendLine("line 3")
builder.AppendLine("line 4")

If you specifically need the CR and LF characters, you should be using the constants in the ControlChars class instead of the old vbCrLf constant.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
2

You say VB, but have tagged with VB.NET. Your question is slightly odd as well. Different OSes actually require different newline characters. What you want is Environment.NewLine. This will give you the correct new line character(s) no matter what OS the .NET framework is running on.

Dale Myers
  • 2,703
  • 3
  • 26
  • 48
2

I still using the old fashioned chr(13) for example:

"Hello" & chr(13) & "World"

It results in:

Hello
World

EDIT: Like Dave Doknjas said, in your case it would be chr(10) to feed the line.

Allan Wells
  • 81
  • 1
  • 13
0

If you're looking for an inline escape to accomplish something like including line breaks in a String.Format you can include a pipe or something similar and then replace it at the end of your string.

String.Format("Batch: {0} | ProductNumber: {1} | Formula: {2}", dr.Item("BatchNumber"), dr.Item("PartNum"), dr.Item("Formula")).Replace("|", Environment.NewLine)

EllieK
  • 259
  • 4
  • 14