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.

0

8 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
2

I think what you're looking for is:

textBox1.Select();

in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)

From :

Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown TextBox1.Select()
End Sub

Using Focus method

 Private Sub frmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load yourControl.Focus() End Sub
1

Quite simple :

For the tab control, you need to handle the _SelectedIndexChanged event:

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _ Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedTab.Name = "TabPage1" Then TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then TextBox4.Focus()
End If

To set focus,

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) TextBox1.Focus()
End Sub

Set the TabIndex by

Me.TextBox1.TabIndex = 0
1

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

create a textbox:

 <TextBox Name="tb"> ..hello..
</TextBox>

focus() ---> it is used to set input focus to the textbox control

tb.focus()

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like