#939 – Retrieving Individual Lines of Text from a TextBox

The LineCount property of a TextBox can be used to retrieve the current number of lines of text in a TextBox.  If the text wraps to multiple lines, this property will reflect the visible number of wrapped lines that the user sees.

The TextBox.GetLineText method allows reading an individual line of text based on a 0-based index.

Assume that we have a TextBox that wraps some text:

        <TextBox Name="txtTest" Margin="5" Height="100"
            Text="{Binding SomeText}"
            TextWrapping="Wrap"
            SelectionBrush="Purple"
            VerticalScrollBarVisibility="Auto"/>
        <Button Content="Inspect" Click="Button_Click"
            HorizontalAlignment="Center" Padding="10,5"/>

We can then read each visible line when the button is clicked.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sbInfo = new StringBuilder(string.Format("# lines = {0}", txtTest.LineCount));
            sbInfo.AppendLine();

            for (int i = 0; i < txtTest.LineCount; i++)
                sbInfo.AppendLine(txtTest.GetLineText(i));

            MessageBox.Show(sbInfo.ToString());
        }

939-001
If we change the size of the TextBox, causing the lines to wrap differently, the LineCount will change.

939-002