#937 – Selecting Text in a TextBox from Code

You can select text in a TextBox from code by using the Select method.  This method accepts the following two parameters:

  • start – 0-based index for start of selection (int)
  • length – number of characters to select (int)

Note that if the TextBox doesn’t currently have focus, the selected text will not be highlighted.

Assume that we have a TextBox, some labels displaying selected text and a Button:

        <TextBox Name="txtTest" Margin="5" Height="100"
            Text="{Binding SomeText}"
            TextWrapping="Wrap"
            VerticalScrollBarVisibility="Auto"
            SelectionChanged="TextBox_SelectionChanged"/>
        <Label Content="{Binding SelectedText}"/>
        <StackPanel Orientation="Horizontal">
            <Label Content="{Binding SelectionStart}"/>
            <Label Content="{Binding SelectionLength}"/>
        </StackPanel>
        <Button Content="Select Something" Click="Button_Click"/>

The code below then selects some text when the button is pressed.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Select 10 characters, starting 6th character
            txtTest.Select(5, 10);

            // Give focus back to TextBox, so that it
            // highlights selected text
            txtTest.Focus();
        }

937-001

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: