4

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Alek
  • 41
  • 1
  • 2
  • 1
    Welcome to Stack Overflow. This is a good first question. – John Oct 01 '12 at 23:01
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Oct 02 '12 at 01:26

3 Answers3

6

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.

EricLaw
  • 56,563
  • 7
  • 151
  • 196
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
3

It is possible to get the line count and build an array of lines directly. This is inclusive of lines generated due to WordWrap.

// Get the line count then loop and populate array
int lineCount = textBox1.GetLineFromCharIndex(textBox1.Text.Length) + 1;

// Build array of lines
string[] lines = new string[lineCount];
for (int i = 0; i < lineCount; i++)
{
    int start = textBox1.GetFirstCharIndexFromLine(i);
    int end = i < lineCount - 1 ? 
        textBox1.GetFirstCharIndexFromLine(i + 1) :
        textBox1.Text.Length;                            
    lines[i] = textBox1.Text.Substring(start, end - start);
}
blins
  • 2,515
  • 21
  • 32
0

You can pull out the single string and then do whatever you want with it.

Splitting a string into a list of strings based on a separator is straightforward:

https://stackoverflow.com/a/1814568/13895

Community
  • 1
  • 1
John
  • 15,990
  • 10
  • 70
  • 110