Problem to set focus in control

priscilla

New member
Joined
Nov 29, 2005
Messages
1
Programming Experience
1-3
Iam working in VB.net , i want to set focus to a textbox which is within a groupbox, during form load. How can i do it. Plz help me.
 
Welcome to the forum priscilla.
I had this same problem and I'm not exactly sure why but setting the focus during a form's load event didn't work for me. I believe it's because after the load event occurs, the focus is set to the control with the lowest TabIndex (actually the control with the lowest tabIndex that can receive focus, certain controls such as the Label and GroupBox can't receive focus).
So, to set the focus to a certain textbox after the form loads (not during load) set that textbox's TabIndex to the lowest value.
It becomes more complex when the textbox is contained within a groupbox or other container control. If there are other controls that can receive the focus outside of the groupbox, you'll need to set the GroupBox's TabIndex to a value lower than those controls outside of the GroupBox.
Visual Studio gives you a graphical way to set the tabIndex by selecting 'View' -> 'Tab Order' from the main menu. See a post by jmcilhinney with more detailed instruction by clicking here.
 
If it is inconvenient to alter the Tab order, which it may well be, you can use the Activated event instead of the Load event as it is raised after the form becomes visible. Note that the Activated event can be raised more than once for a form though, so you must identify the first time:
VB.NET:
    Private initialised As Boolean = False

    Private Sub Form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Activated
        If Not Me.initialised Then
            Me.myTextBox.Focus()
            Me.initialised = True
        End If
    End Sub
 
Back
Top