Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting focus to a textbox control

If I want to set the focus on a textbox when the form is first opened, then at design time, I can set it's tabOrder property to 0 and make sure no other form control has a tabOrder of 0.

If I want to achieve the same result at run-time, using code, how should I proceed?
Are there alternatives to using tabOrder?
I assume any run-time code will be in the form's constructor or its onload event handler?


EDIT
In other words I'd like to be able to type straight into the textbox as soon as the form appears without having to manually tab to it, or manually select it.

like image 438
whytheq Avatar asked Apr 30 '13 07:04

whytheq


People also ask

What is TextBox focus?

A TextBox allows the player to provide text input. It behaves similarly to a TextButton, except that a single TextBox can be put in focus by clicking, tapping or gamepad selection. While in focus, the player can use a keyboard to change the Text property. If there is no text, the PlaceholderText will be visible.

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

How do you use TextBox control?

On the Design tab, in the Controls group, click Text Box. Position the pointer where you want the text box to be placed on the form or report, and then click to insert the text box. Note: Access also places a label to the left of the text box, so leave some room to the left of the pointer for the label.

How do you use set focus?

Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object. To read some of the properties of a control, you need to ensure that the control has the focus. For example, a text box must have the focus before you can read its Text property.


2 Answers

Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form

Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Me.Show()
    TextBox1.Select()
End Sub
like image 72
Robert Beaubien Avatar answered Sep 21 '22 15:09

Robert Beaubien


I think the appropriate event handler to use is "Shown". And you only need to focus the appropriate text box.

Private Sub Me_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
    myTextbox.Focus()
End Sub
like image 22
Giorgio Barchiesi Avatar answered Sep 22 '22 15:09

Giorgio Barchiesi