0

I've created a griddefinition in my .xaml file.

The size value (_lattice.size) for the grid only emerges at runtime. How can I dynamically fill the grid up with rows and columns and also place buttons in every single cell of the button grid?

My attempt:

//.xaml

<Grid x:FieldModifier="public" x:Name="_tableGrid">


</Grid>

//code-behind file (c#)

private void GenerateTable(string filepath)
{
            GamePage.statusLabel.IsVisible = true;
            GamePage.buttonStartStop.IsVisible = true;

            _initializeTerminate.InitializeGame(filepath, _lattice, _snake, _egg);

            for(Int32 k = 0; k < _lattice.size; k++)
            {
                var r = new RowDefinition();
                r.Height = 50;
                GamePage._tableGrid.RowDefinitions.Add(r);
                
            }
            for(Int32 l = 0; l < _lattice.size; l++)
            {
                var c = new ColumnDefinition();
                c.Width = 50;
                GamePage._tableGrid.ColumnDefinitions.Add(c);
            }
            for (Int32 i = 0; i < _lattice.size; i++)
            {
                
                for (Int32 j = 0; j < _lattice.size; j++)
                {
                    _lattice.button_lattice[j * _lattice.size + i] = new Button();

                    _lattice.button_lattice[j * _lattice.size + i].Background = Brush.White;
                    _lattice.button_lattice[j * _lattice.size + i].BorderWidth = 1.0;
                    _lattice.button_lattice[j * _lattice.size + i].BorderColor = Color.Yellow;


                 GamePage._tableGrid.Children.Add(_lattice.button_lattice[j * _lattice.size + i]);
                    
                }
            }
}

Unfortunately, the above code does not generate the desired behaviour. It seems that there is only a single button present on the screen.

curiousMind_85
  • 167
  • 1
  • 8
  • 1
    Does this answer your question? [How to set Grid row and column positions programmatically](https://stackoverflow.com/questions/3745594/how-to-set-grid-row-and-column-positions-programmatically) or https://stackoverflow.com/questions/61304708/xamarin-forms-add-children-programmatically-to-certain-column-of-grid – Klaus Gütter Dec 22 '21 at 12:03
  • you are not specifying the row and col values when you add the Button. https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.grid.igridlist-1.add?view=xamarin-forms#Xamarin_Forms_Grid_IGridList_1_Add_Xamarin_Forms_View_System_Int32_System_Int32_ – Jason Dec 22 '21 at 12:06

0 Answers0