0

I'm trying to create a text box which will have a limit of characters per line and creating new lines if this limit is reached. Right now I'm trying to loot at SelectionStartin KeyUp and determine if user is position where the he should go the next line then I'm just moving him to the next line until he'll reach a certain lines limit.

Logic for this is surprisingly complex. I have to look if I the last thing in the line is word and no separator in the end I need to move to the next line and merge with the next line and check if the next line isn't too long, etc. All of it isn't working all that well which is not a surprise. Plus too many manipulations with strings are as fast as I'd like to even using StringBuilder.

Is there any easier way to do something like this?

user3223738
  • 447
  • 1
  • 4
  • 12
  • 1
    Do you just need the lines to wrap on the display or do you need to store the input with line breaks? If it is just for display, the TextBox has a WordWrap property that may get you what you need. If you need to store the data with WordWrap (linebreaks) then [this](http://stackoverflow.com/questions/12682209/textbox-word-wrapping-splitting-string-to-lines) link may help. [Here](http://stackoverflow.com/questions/3938998/wrapping-text-in-a-rich-textbox-but-not-word-wrapping-it) is another one that might help. –  Dec 17 '14 at 12:51
  • I need to store than with line breaks in .Text. Thanks for the, I'll check it. – user3223738 Dec 17 '14 at 12:55
  • You could take a look at this post http://stackoverflow.com/questions/26847867/limit-characters-per-line-in-the-multiline-textbox-in-windows-form-application There might be an answer to a similar question – barca_d Dec 17 '14 at 14:59

2 Answers2

0

If the visual effect is not critical, you can allow string to be entered freely. At Save, you can then use the substring() method in a loop to achieve the desired row lengths and insert '\n' as required

Justjyde
  • 322
  • 1
  • 3
  • 13
0

You should be able to do this, at the keyup event of the textbox:

string[] lines = textbox1.Text.Replace(Environment.Newline, "\n").Split('\n');
if (lines.Count > 10)
{
    // More than 10 lines. Show an error or something
    e.Handled = true;
    e.SuppressKeyPress = true;
    return
}

if (lines.Any(z => z.Length > 100))
{
    // More then 100 character on a line. Do Something
    e.Handled = true;
    e.SuppressKeyPress = true;
    return;
}

Of course, change the 10 to however many lines you want and 100 to the max length you want each line to be.

Icemanind
  • 47,519
  • 50
  • 171
  • 296