C# – focus to text box

c++

I created a form with a label, textbox and a button. In the form load event I called the focus() function for the textbox. But when I run my code the cursor is not coming to textbox. I need the cursor to go to text box as soon as the form is loaded. How to do it?

Best Solution

If you simply need to make sure a certain control gets focus when you first load a form, then change the TabOrder properties of all your controls (in the Designer) so that the control in question is '0', and the other elements are going up from there, '1', '2', etc.

If you need to dynamically select a different control when you show a form depending on some condition, then use the following code:

private void Form1_Load(object sender, EventArgs e) {
    // You need to show the form otherwise setting focus does nothing 
    // (there are no controls to set focus to yet!)
    this.Show()
    if (someCondition == true)
        control.Focus();
    else
        control2.Focus();
}