Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBox Word-Wrapping splitting string to lines

This is my first time posting question on this amazing service, since today it has helped me a lot by just reading it.

Currently, I'm making small C# application where I need to use a lot of TextBoxes. In TextBox Properties I have checked MultiLine and Word-Wrap functions. So when user enters text, it is displayed correctly in multiple lines.

My problem is how can I get those lines, which are displayed on form, in list of strings, instead of one big string.

I haven yet distinguished weather Word-Wrap Function makes new lines or adds "\n\r" at the end of every line. I tried to get lines from TextBox.Lines , but it has only TextBox.Lines[0], which contains the whole string form TextBox

I have already tried many things and researched many resources, but I still haven't found right solution for this problem.

like image 363
Alek Avatar asked Jan 15 '23 10:01

Alek


1 Answers

Lots of corner cases here. The core method you want use is TextBox.GetFirstCharIndexFromLine(), that lets you iterate the lines after TextBox has applied the WordWrap property. Boilerplate code:

    var lines = new List<string>();
    for (int line = 0; ;line++) {
        var start = textBox1.GetFirstCharIndexFromLine(line);
        if (start < 0) break;
        var end = textBox1.GetFirstCharIndexFromLine(line + 1);
        if (end == -1 || start == end) end = textBox1.Text.Length;
        lines.Add(textBox1.Text.Substring(start, end - start));
    }
    // Do something with lines
    //... 

Beware that line-endings are included in lines.

like image 119
Hans Passant Avatar answered Jan 28 '23 19:01

Hans Passant