don
don

Reputation: 203

Inserting line breaks in a string dynamically

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.

Upvotes: 2

Views: 1373

Answers (1)

Alberto Monteiro
Alberto Monteiro

Reputation: 6249

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.

Upvotes: 3

Related Questions