Share via


How to: Select Text in the Windows Forms TextBox Control

You can select text programmatically in the Windows Forms TextBox control. For example, if you create a function that searches text for a particular string, you can select the text to visually alert the reader of the found string's position.

To select text programmatically

  1. Set the SelectionStart property to the beginning of the text you want to select.

    The SelectionStart property is a number that indicates the insertion point within the string of text, with 0 being the left-most position. If the SelectionStart property is set to a value equal to or greater than the number of characters in the text box, the insertion point is placed after the last character.

  2. Set the SelectionLength property to the length of the text you want to select.

    The SelectionLength property is a numeric value that sets the width of the insertion point. Setting the SelectionLength to a number greater than 0 causes that number of characters to be selected, starting from the current insertion point.

  3. (Optional) Access the selected text through the SelectedText property.

    The code below selects the contents of a text box when the control's Enter event occurs. The TextBox1_Enter event handler must be bound to the control; for more information, see How to: Create Event Handlers at Run Time for Windows Forms.

    Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter
       TextBox1.SelectionStart = 0
       TextBox1.SelectionLength = TextBox1.Text.Length
    End Sub
    
    private void textBox1_Enter(object sender, System.EventArgs e){
       textBox1.SelectionStart = 0;
       textBox1.SelectionLength = textBox1.Text.Length;
    }
    
    private void textBox1_Enter(Object sender, System.EventArgs e) 
    {
       textBox1.set_SelectionStart(0);
       textBox1.set_SelectionLength(textBox1.get_Text().get_Length());
    }
    
    private:
       void textBox1_Enter(System::Object ^ sender,
          System::EventArgs ^ e)
       {
          textBox1->SelectionStart = 0;
          textBox1->SelectionLength = textBox1->Text->Length;
       }
    

See Also

Tasks

How to: Control the Insertion Point in a Windows Forms TextBox Control
How to: Create a Password Text Box with the Windows Forms TextBox Control
How to: Create a Read-Only Text Box (Windows Forms)
How to: Put Quotation Marks in a String (Windows Forms)
How to: View Multiple Lines in the Windows Forms TextBox Control

Reference

TextBox Control Overview (Windows Forms)
TextBox

Other Resources

TextBox Control (Windows Forms)