How to: Set the Selected Text in a TextBox Control

This example programmatically selects text in a Windows Forms TextBox control and retrieves the selected text.

Example

private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = "Hello World";
    textBox1.Select(6, 5);
    MessageBox.Show(textBox1.SelectedText);
}

Compiling the Code

This example requires:

  • A form with a TextBox control named textBox1 and a Button control named button1. Set the Click event handler of button1 to button1_Click.

    Note

    The code can also be used with a RichTextBox control by substituting a RichTextBox control named richTextBox1 for the TextBox control and changing the code from textBox1 to richTextBox1.

Robust Programming

In this example you are setting the Text property before you retrieve the SelectedText value. In most cases, you will be retrieving text typed by the user. Therefore, you will want to add error-handling code in case the text is too short.

See Also

Concepts

Designing a User Interface in Visual C#

Other Resources

Text Controls

Visual C# Guided Tour