How to SetFocus on a TextBox in the Form Load

hawbsl picture hawbsl · Feb 25, 2011 · Viewed 28.4k times · Source

Working in both A2003 & A2007.

How do we ensure that a selected TextBox gets the focus when the form loads? If we put MyTextBox.SetFocus in the Form_Load then we get the error:

can't move the focus to the control

This form is designed for rapid data entry, and the form somewhat rearranges itself based on the last used settings. So there are several different textboxes any of which may need the focus depending on the user. We can't just fix it in design time by giving MyTextBox TabIndex=0.

The help says something about calling Repaint which just doesn't make any sense at all:

You can move the focus only to a visible control or form. A form and controls on a form aren't visible until the form's Load event has finished. Therefore, if you use the SetFocus method in a form's Load event to move the focus to that form, you must use the Repaint method before the SetFocus method.

Answer

Fionnuala picture Fionnuala · Feb 25, 2011

The best bet in this case, is to ensure that the textbox to get focus is numbered 0 in the Tab Index property.