简体   繁体   中英

Characters per line and lines per TextBox in WinForms

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 SelectionStart in 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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM