#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: