How to: Retrieve a Text Selection

This example shows one way to use the SelectedText property to retrieve text that the user has selected in a TextBox control.

Define a TextBox control

The following Extensible Application Markup Language (XAML) example shows the definition of a TextBox control that contains some text to select, and a Button control with a specified OnClick method.

In this example, a button with an associated Click event handler is used to retrieve the text selection. When the user clicks the button, the OnClick method copies any selected text in the textbox into a string. The particular circumstances by which the text selection is retrieved (clicking a button), as well as the action taken with that selection (copying the text selection to a string), can easily be modified to accommodate a wide variety of scenarios.

<TextBox Name="tbSelectSomeText">
  Some text to select...
</TextBox>

<Button Click="OnClick">Retrieve Selection</Button>

OnClick event handler

The following C# example shows an OnClick event handler for the button defined in the XAML for this example.

void OnClick(object sender, RoutedEventArgs e)
{
    String sSelectedText = tbSelectSomeText.SelectedText;
}
Private Sub OnClick(ByVal senter As Object, ByVal e As RoutedEventArgs)
    Dim sSelectedText As String = tbSelectSomeText.SelectedText
End Sub

See also