How to: Get a Collection of Lines from a TextBox

This example shows how to get a collection of lines of text from a TextBox.

Example

The following example shows a simple method that takes a TextBox as the argument, and returns a StringCollection containing the lines of text in the TextBox. The LineCount property is used to determine how many lines are currently in the TextBox, and the GetLineText method is then used to extract each line and add it to the collection of lines.

StringCollection GetLinesCollectionFromTextBox(TextBox textBox)
{
    StringCollection lines = new StringCollection();

    // lineCount may be -1 if TextBox layout info is not up-to-date.
    int lineCount = textBox.LineCount;

    for (int line = 0; line < lineCount; line++)
        // GetLineText takes a zero-based line index.
        lines.Add(textBox.GetLineText(line));

    return lines;
}

See Also

Concepts

TextBox Overview

RichTextBox Overview