Export (0) Print
Expand All

Controlling the Insertion Point in a Windows Forms TextBox Control

Visual Studio .NET 2003

When a Windows Forms TextBox control first receives the focus, the default insertion within the text box is to the left of any existing text. The user can move the insertion point with the keyboard or the mouse. If the text box loses and then regains the focus, the insertion point will be wherever the user last placed it.

In some cases, this behavior can be disconcerting to the user. In a word processing application, the user might expect new characters to appear after any existing text. In a data entry application, the user might expect new characters to replace any existing entry. The SelectionStart and SelectionLength properties allow you to modify the behavior to suit your purpose.

To control the insertion point in a TextBox control

  1. Set the SelectionStart property to an appropriate value. Zero places the insertion point immediately to the left of the first character.
  2. (Optional) Set the SelectionLength property to the length of the text you want to select.

    The code below always returns the insertion point to 0. The TextBox1_Enter event handler must be bound to the control; see Creating Event Handlers at Run Time for Windows Forms for more information.

    ' Visual Basic
    Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter
       TextBox1.SelectionStart = 0
       TextBox1.SelectionLength = 0
    End Sub
    
    // C#
    private void textBox1_Enter(Object sender, System.EventArgs e) {
       textBox1.SelectionStart = 0;
       textBox1.SelectionLength = 0;
    }
    
    // C++
    private:
       System::Void textBox1_Enter(System::Object *  sender,
          System::EventArgs *  e)
       {
          textBox1->SelectionStart = 0;
          textBox1->SelectionLength = 0;
       }
    

The TextBox insertion point is visible by default in a new form only if the TextBox control is first in the tab order. Otherwise, the insertion point appears only if you give the TextBox the focus with either the keyboard or the mouse.

To make the text box insertion point visible by default on a new form

  • Set the TextBox control's TabIndex property to 0.

See Also

Introduction to the Windows Forms TextBox Control | Creating a Password Text Box with the Windows Forms TextBox Control | Creating a Read-Only Text Box (Windows Forms) | Putting Quotation Marks in a String Programmatically (Windows Forms) | Selecting Text Programmatically in the Windows Forms TextBox Control | Viewing Multiple Lines in the Windows Forms TextBox Control | TextBox Class | TextBox Control (Windows Forms)

Show:
© 2015 Microsoft