TextBoxBase.Select Method (Int32, Int32)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Selects a range of text in the text box.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public void Select(
	int start,
	int length


Type: System.Int32

The position of the first character in the current text selection within the text box.

Type: System.Int32

The number of characters to select.

Exception Condition

The value of the start parameter is less than zero.

If you want to set the start position to the first character in the control's text, set the start parameter to 0. You can use this method to select a substring of text, such as when searching through the text of the control and replacing information.


You can programmatically move the caret within the text box by setting the start parameter to the position within the text box where you want the caret to move to and set the length parameter to a value of zero (0). The text box must have focus in order for the caret to be moved.


If this method is called without any parameters, an alternative method is used. This alternative method inherits from the Control class. When called, it sets the input focus to the control and selects the contents of the control. For more information, see the Control.Select method.

The following code example uses TextBox, a derived class, to search the contents of the control for the instance of the word "fox". If found, the code selects the word in the control using the Select method. This example requires that a TextBox named textBox1 has been created and its Text property contains the sentence "The quick brown fox jumps over the lazy dog."

public void SelectMyString()
    // Create a string to search for the word "fox".
    String searchString = "fox";
    // Determine the starting location of the word "fox".
    int index = textBox1.Text.IndexOf(searchString, 16, 3);
    // Determine if the word has been found and select it if it was.
    if (index != -1)
       // Select the string using the index and the length of the string.
       textBox1.Select(index, searchString.Length);

.NET Framework
Available since 1.1
Return to top