#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 software development and sailing.

Leave a comment