Loop through all controls in a page switches the control indexes

Laoujin

Registered User.
Local time
Today, 03:52
Joined
Jul 25, 2005
Messages
16
Hey all,

I'm writing an application that automatically adds code, events and formats the controls on a form.

Basically I'm looping through all the controls like this:
For Each ctr in frm.Controls
Loop

I also tried:
For i = 0 to frm.Controls.Count -1
Set ctr = frm.controls.item(i)
Next

The issue I'm having is that it is processing the same control several times and when a control is being processed for the second time, another control is being skipped.

What happens is that a control at for example index 4 is processed, then it reappears at index 24. At that point the control at index 4 is another one.

I assume this happens because the controls are renamed and then the form control indexes are rearranged.

Anyone knows a workaround or know more about the reindexing?
 
You say you are adding event code. And possibly other code. But are you adding controls or changing the nature of the controls? Format changes and event code changes don't do what you described.

What you describe is abnormal behavior, bad enough that I think you must have tried to add a control. Once a control is created, as long as you don't rename it, it should stay good - and stay with the same number. But then, you don't say what version of Access you are using. I'll say this. I used to do stuff like you just described and I have never had that problem, but the last time I had to do that was with Ac97. Since then, my database stuff has been in a different direction.

Changing control properties shouldn't do anything to a control's position in the me!controls collection. On the other hand, if you are going to rename a control, you can use this concept...

Me!Controls(newname)

to reference the renamed control. I'll be honest, if I were going to rename controls, I'd be sure to do the renaming first so that the list will be stable alphabetically. Then I'd go back and do the other things I wanted to do.

On the other hand, there is NO WAY the index of the control should change unless you are physically restructuring the whole form, not just the properties of the controls on that form. You have GOT to be doing something wrong to the controls collection.
 
I'm working with Access 2003.

I'm not adding any new controls. I'm not sure what you mean with "changing the nature of the controls" but I'm not changing a TextBox to a ComboBox (If such a thing is possible in the first place)

But I *am* changing the names of the controls. The "weird" part is that when I run the code for the first time, that is when all controls have their default names, it works properly. If I then add controls and run the code again this issue comes up.

I can work around this with some extra code, it's just that a For Each loop should loop through all controls, no matter what.
 

Users who are viewing this thread

Back
Top Bottom