Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

To add newline in a text box control in C#

Normally, when you want to add newline to a string you can use'\n' for adding new lines like below.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Text;
  5. using System.Windows.Forms;
  6.  
  7. namespace FirstProgram
  8. {
  9. public partial class Form2 : Form
  10. {
  11. public Form2()
  12. {
  13. InitializeComponent();
  14. }
  15.  
  16. private void Form2_Load(object sender, EventArgs e)
  17. {
  18. string sample = "I am \n coming \n from \n Forget Code";
  19. MessageBox.Show(sample);
  20. txtSample.Text = sample;
  21. }
  22. }
  23. }


Output: (In Message box only)
I am
coming
from
Forget Code


In Message box you can see the newline but not in the text box.


If you want to add newline for a text box, you can not simply use '\n', rather you can use Environment.NewLine.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Text;
  5. using System.Windows.Forms;
  6.  
  7. namespace FirstProgram
  8. {
  9. public partial class Form2 : Form
  10. {
  11. public Form2()
  12. {
  13. InitializeComponent();
  14. }
  15.  
  16. private void Form2_Load(object sender, EventArgs e)
  17. {
  18. string sample = "I am \n coming \n from \n Forget Code";
  19. MessageBox.Show(sample);
  20.  
  21. string newLine = Environment.NewLine;
  22.  
  23. txtSample.Text = "I am"+newLine+"coming"+newLine+" from " +newLine+ "Forget Code";
  24. }
  25. }
  26. }


Output: (Both in Message box and text box)

I am
coming
from
Forget Code