When showing a form that contains a TextBox, it’s common courtesy to focus the TextBox so that the user can begin typing immediately.

To focus a TextBox when a Windows Form first loads, simply set the TabIndex for the TextBox to zero (or the lowest TabIndex for any Control on the Form).

When a Form is displayed, it automatically focuses the Control with the lowest TabIndex.  Note that if your TextBox is pre-initialized with some text, then the entire Text will be selected, as shown below:

Entire text is selected

If you want to change the selection behavior so that none of the text is selected and the cursor appears before the text, then you must override the Form’s OnShown method as follows:

protected override void OnShown( EventArgs e )
{
    this.textBox1.SelectionLength = 0;
    base.OnShown( e );
} 

To make the cursor appear after the text:

Cursor appears after text

protected override void OnShown( EventArgs e )
{
    this.textBox1.SelectionLength = 0;
    this.textBox1.SelectionStart = this.textBox1.Text.Length;
    base.OnShown( e );
} 
Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot