.NET GroupBox controls and the reverse ordering of numbers

So, I found this interesting thing happening in the way .NET orders controls to a collection. I am not talking TabIndex here.

I was working on this little app that has a GroupBox on a form. I added some radiobuttons to the groupbox. When a user updates the data on the form, I have some logic that loops through and figures out which radiobutton in the group box is selected. I could determine this other ways, but for demonstration purposes (I was teaching some developers about some of the controls) I did it this way.

Anywhooo, I loop through and pick up the number of the control that is checked. So, if I have 3 radiobuttons in the box, and the third one is selected, then it is Item number 2 that is selected (zero-based collection). It just so happens (not coincidentally) that this number matches a value in an enumeration in a class the app uses. So, selected radiobutton 2 means setting the enum value to 2. The convenient matching saves me code writing. The names of the radiobuttons match the names in the enum. Let’s say this is my enum.

     Public Enum PolicyStatusVals

           Active = 0

           Inactive = 1

           Terminated = 2

     End Enum

I then have three rb’s, one names rbActive, one rbInactive, etc. What I found was that when I place the rb’s in the groupbox, they become part of the controls collection, but the first becomes last and the last becomes first (it’s kind of Biblical). In other words, if I want rbActive to be Item 0, then I need to add it last. It seems that the way the collection is built is that it stacks items in sequentially, adding new ones to the begging of the queue.

I am going to investigate this a little further when I get some email done. I suspect that there is a specific way collections work in .NET that make this so, and it probably applies to a broader scope. It surprised me a little, however. I figured that the last one in would be the highest number.