2

I have a TextBox where I need to show some text. The length of the text is dynamic, so it needs to be wrapped to fit into multiple lines.

The maximum length of a line is 50 characters. If the text is more than that, I need to add a line break \n.

For example, if the text is 165 chars:

  1. Add a \n at 51st position
  2. Add a \n at 102nd position
  3. Add a \n at 153rd position

So finally the total length of text will be 168 chars.

I know how to do this using a loop. But my question is, can this be done without much code? Does the String class have a method to provide that function?

This is a Windows Forms app, but all controls including TextBox are created programmatically.

3
  • Environment.NewLine does not help? Commented Dec 31, 2015 at 0:49
  • what type of application is it? Commented Dec 31, 2015 at 0:59
  • You don't mind putting a line break in the middle of a word? Commented Dec 31, 2015 at 2:34

1 Answer 1

3

For Windows Forms application

You can use the WordWrap property, set it to true.

If you want to do it dynamically

You can do this in code, using this:

myTextBox.WordWrap = true; myTextBox.Multiline = true; 

If you want to do it in UI

Select the textbox and then press F4. Search for WordWrap, and set it to true.

Also don't forget to set your TextBox as Multiline

Working sample

@Don since you said that using WordWrap doesn't work for you, you can try using regex, like the code below:

using System.Linq; using System.Text.RegularExpressions; private void Form1_Load(object sender, EventArgs e) { var textBox = new TextBox { Multiline = true, WordWrap = false, Width = 295, Height = 100, ReadOnly = true }; var textFromDatabase = "1234567890 1234567890 1234567890 1234567890 111150dasdasds1234567890 1234567890 1234567890 1234567890 111150dasdasds1234567890 1234567890 1234567890 1234567890 1111"; var strings = Regex.Matches(textFromDatabase, ".{0,50}"); var lines = strings.Cast<Match>() .Select(m => m.Value) .Where(m => !string.IsNullOrWhiteSpace(m)); var @join = string.Join(Environment.NewLine, lines); textBox.Text = @join; Controls.Add(textBox); } 

Note that I'm creating a TextBox with WordWrap false and Multiline = true.

Sign up to request clarification or add additional context in comments.

28 Comments

how do you suggest without knowing the type of application?
@un-lucky I tried it, he said "TextBox" and also mentioned "\n", so I thought that is a Win Form app, it could be a WPF, but I will change my question, thanks for advise!!
User top tags: Winform
@user1501127 Well noted!!
It's a Win Forms app, but there's no designer used here. All controls including TextBox's are created dynamically in code.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.