hawbsl
hawbsl

Reputation: 16003

How to SetFocus on a TextBox in the Form Load

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.

Upvotes: 4

Views: 30815

Answers (4)

Fionnuala
Fionnuala

Reputation: 91306

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

Upvotes: 2

HansUp
HansUp

Reputation: 97101

Move SetFocus to the form's On Current event. Should work then unless perhaps the form's record source contains no records and you've set the form's Allow Additions property to No. In that case your text box will not be available to SetFocus on, but in my testing it doesn't throw an error.

Upvotes: 1

mwolfe02
mwolfe02

Reputation: 24207

In my experience, I've always gotten that error when the control I was trying to set focus to was either 1)not visible or 2)not enabled. I assume you've already checked those, but it would be worth double checking at runtime when you get the error message (especially since you said you are shuffling the controls at runtime).

I use the .SetFocus method pretty regularly without trouble. I don't recall ever getting an error message when setting focus to a control that already has it as Remou stated in his answer.

I believe there is also a third case that occurs if you try to set focus to a control in the form header/footer of a bound form that has had all of its records filtered out. I know that situation causes "disappearing" contents in an unbound combo box, but I think it may also play havoc with the SetFocus method. If you are opening the form in Data Entry mode, though, that should not be an issue.

Upvotes: 1

Kevin Ross
Kevin Ross

Reputation: 7215

You cant set the focus as the controls don’t really exist yet, try putting the code in the OnActivate event instead

Or just put a DoCmd.Repaint in the OnLoad event before trying to set the focus. Both should work but I'm not near a computer to check

Upvotes: 1

Related Questions