Vb.net – Can’t set focus on a Windows Forms textbox

vb.netwinforms

I can't seem to get input focus on a textbox when a tab page first comes up (I'm using Windows Forms, VB.NET 3.5).

I have a textbox on a panel on a tab page, and I want the focus to be on the textbox when the tab page comes up. I want the user to be able to start typing immediately in the focused textbox without having to click on the textbox. I have tab stops set in the order I want and the textbox is the first tab stop. The tab stops work except that when the tab page comes up the focus is not on the textbox, i.e. the one that's first in the tab order.

In the Enter event handler of the tab page I call the Focus method of the text box, but it returns False and does nothing, no error messages. I know I can access the text box because
at the same point in the code I can set the text of the text box.

If it matters, the layout of the tab page is a little complicated:

frmFoo/TabControl1/TabPageX/Panel1/Panel2/TextBox1

I want to set the focus on TextBox1.

  1. What's the best way to get the focus on the desired textbox?
  2. If setting focus is the best way, why is the textbox.Focus() method failing?

Best Answer

I would assume you are attempting to set focus in the form load event handler? If so, you need to do a Me.Show() to actually create the onscreen controls before focus can be set. Something along the lines of:

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

If you don't do the Me.Show(), the form is NOT displayed until the load event is complete.

For the tab control, 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

You will still want to set the initial focus in the load event as shown above if the first field selected is to be the textbox on the tab control.