how to put focus on TextBox when the form load?

I have in my C# program textBox

I need that when the program start, the focus will be on the textBox

I try this on Form_Load:

MyTextBox.Focus();

but it wont work


Solution 1:

Set theActiveControl property of the form and you should be fine.

this.ActiveControl = yourtextboxname;

Solution 2:

check your tab order and make sure the textbox is set to zero

Solution 3:

You cannot set focus to a control if it has not been rendered. Form.Load() occurs before the controls are rendered.

Go to the form's events and double click the "Shown" event. In the form's shown event handler call the control.Focus() method.

    private void myForm_Shown(object sender, EventArgs e)
    {
        // Call textbox's focus method
        txtMyTextbox.Focus();
    }

Solution 4:

You could try:

MyTextBox.Select();

According to the documentation:

The Select method activates the control if the control's Selectable style bit is set to true in ControlStyles, it is contained in another control, and all its parent controls are both visible and enabled.

You can first check if the control can be selectable by inspecting the MyTextBox.CanSelect property.

Solution 5:

If you only want to set the focus the first time the form is shown, try handling the Form.Shown event and doing it there. Otherwise use Control.VisibleChanged.