Reputation: 203
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:
\n
at 51st position\n
at 102nd position\n
at 153rd positionSo 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
Reputation: 6249
You can use the WordWrap property, set it to true.
You can do this in code, using this:
myTextBox.WordWrap = true;
myTextBox.Multiline = true;
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
@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