Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set focus on a Windows Forms textbox

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?
like image 423
RaleighBoy Avatar asked Jun 09 '11 02:06

RaleighBoy


2 Answers

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.

like image 66
Robert Beaubien Avatar answered Sep 30 '22 19:09

Robert Beaubien


Do the control.Focus() in the OnShown event. You don't need any of the DoEvents logic which didn't work for me anyway.

like image 38
BillJam Avatar answered Sep 30 '22 17:09

BillJam