Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put focus on TextBox when the form load?

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

this.ActiveControl = yourtextboxname;

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


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();
    }

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.


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.


The reason you can't get it to work is because the Load event is called before the form is drawn or rendered.

It like telling a pizza place how to make your pizza, and then asking them to send you a picture of how much pepperoni is on your pizza before they made it.

using System;
using System.Windows.Forms;

namespace Testing
{
    public partial class TestForm : Form
    {
        public TestForm()
        {
            InitializeComponent();

            Load += TestForm_Load;

            VisibleChanged += TestForm_VisibleChanged;

            Shown += TestForm_Shown;

            Show();

        }

        private void TestForm_Load(object sender, EventArgs e)
        {
            MessageBox.Show("This event is called before the form is rendered.");
        }

        private void TestForm_VisibleChanged(object sender, EventArgs e)
        {
            MessageBox.Show("This event is called before the form is rendered.");
        }

        private void TestForm_Shown(object sender, EventArgs e)
        {
            MessageBox.Show("This event is called after the form is rendered.");
            txtFirstName.Focus();
        }
    }
}

Textbox.Focus() "Tries" to set focus on the textbox element. In case of the element visibility is hidden for example, Focus() will not work. So make sure that your element is visible before calling Focus().