public Groups_Page() { GlobalVariables.connectToDatabase(); InitializeComponent(); List <string> groups = GlobalVariables.returnListGroups(); int totalGroups = groups.Count; int currentRow = 1; int currentColumn = 1; for (var i = 0; i < totalGroups; i++) { Button newGroup = new Button(); newGroup.Content = groups[i]; newGroup.SetValue(Grid.ColumnProperty, currentColumn); newGroup.SetValue(Grid.RowProperty, currentRow); newGroup.Click += new RoutedEventHandler(newGroup_ButtonClick); MainGrid.Children.Add(newGroup); if (i % 3 == 0 && i != 0) { currentRow++; currentColumn = 1; } else { currentColumn++; } } }