Swanne
Swanne

Reputation: 98

Winforms controlling controls

I couldn't think of a coherent search term for my problem so please forgive me if this has been asked before.

I have 24 combo boxes sitting on a panel control, displayed in 4 rows of 6.

After the user defines the value for each combo and hits the "go" button, I add all combo boxes to list so I can use the values in another section of my program.

The problem is that the order the comboboxes are added to the list is messed up, compared to their visual layout on the panel, and I would like to define the order. Currently, it adds the 9th combobox to the list first then the 20th, 2nd, 16th etc etc.

I tried TabIndex but that didnt work.

Before I manually rename and relabel all of the boxes, any other suggestions will be gratefully received.

Upvotes: 1

Views: 39

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

The controls of your form exist in Controls collection of the container controls, for example when you add a Panel and a Button to a Form and two ComboBox to the Panel, then:

  • Form.Controls contains button1 and panel1
  • Panel.Controls contains comboBox1 and comboBox2

Controls are added to the Controls collection, with the same order that you add them to designer. Open designer.cs, look at the end of InitializeComponent to see the order. You can also see/change the order using Document Outline window.

That said, now it should be obvious that panel1.Controls.OfType<ComboBox>() returns combo boxes with the same order that you see in Document Outline (or based on their z-index, and it doesn't have anything to do with their x/y placements).

You may want to order them based on TabIndex, or any other property that you like:

panel1.Controls.OfType<ComboBox>().OrderBy(x=>x.TabIndex)    

Note

In general, if you are going to use those values for a search, instead of relying on the order of values, a much better idea is creating a SearchModel class which has a few properties, the set those properties to the selected value of the corresponding combo box (manually or using databinding) then pass the search model to the other classes.

Upvotes: 1

Related Questions