There is an array of buttons:

Button[,] buttons = new Button[n,n]; 

How to run through all the buttons on the form (or grid), add them to this array? And in general, how will the “run through” of all buttons occur (that is, in what sequence will these buttons be selected)?

  • @Foggy Finder and if there are not only buttons on the form? - Draktharon
  • @Foggy Finder Yes, if not difficult, I would like to receive an array of 5x5 buttons and two labels below, each occupying 2 cells - Draktharon
  • Why do you need it? The square array of buttons looks weird and very WinForms. Describe your real task. - VladD
  • @VladD This is a sapper, and the field size can be selected, respectively, I need to be able to set the grid and place a button in each of its cells - Draktharon
  • @Draktharon: Yeah, I get it. Somewhere on the site was an example, I will find. But you do not need the buttons, the buttons do not behave as you need. - VladD

1 answer 1

I would go the following way:

  1. Find List<Button> allButtons - a list of all elements on the form.
  2. With nested loops, go through the height and width of the form, and check if there is a button at this point (top / left position) (you allButtons.Where() check allButtons.Where() is simple).
  3. If the button is on the same line - add to the two-dimensional array in the same line.
  4. If there are no pixels on this line, but the next is - this is already a new line of a two-dimensional array.

Maybe crooked, but it will work for sure. And you definitely won't miss anything.