Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus to text box

Tags:

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?

like image 204
Vicky Avatar asked Jun 30 '09 05:06

Vicky


People also ask

What is TextBox focus () in C#?

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).

What is focus in text field?

Setting the focus means making the field active so the cursor is blinking and ready to accept text input. This method can also be used to make a text field active when something else happens (see below).


1 Answers

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();
}
like image 146
Matthew Scharley Avatar answered Oct 26 '22 07:10

Matthew Scharley