Reputation: 25
I am currently working an test application to list e.g. Products, but have the problem of not being able to generate the grids dynamically with the corresponding content (for now only labels). I want to generate them right when the Mainpage is called.
I have already gone throughout various tutorials and websites, but couldn't find anything that would help me save my problem. Tried to start the method for creating the grids by assigning it to a button. I have tried allocating the method to the constructor of the MainPage class, but still there won't be anything shown in the final result.
public void CreateDummyGrids()
{
Grid gOut = new Grid();
gOut.RowDefinitions.Add(new RowDefinition());
gOut.RowDefinitions.Add(new RowDefinition());
gOut.RowDefinitions.Add(new RowDefinition());
gOut.ColumnDefinitions.Add(new ColumnDefinition());
gOut.ColumnDefinitions.Add(new ColumnDefinition());
for (int rowIndex = 0; rowIndex < 3; rowIndex++)
{
for (int columnIndex = 0; columnIndex < 2; columnIndex++)
{
var label = new Label
{
Text ="Hello",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
gOut.Children.Add(label, columnIndex, rowIndex);
}
}
}
Upvotes: 1
Views: 6304
Reputation: 65
Grid dynamicGrid = new Grid { Padding= new Thickness(5,5)};
dynamicGrid.RowDefinitions.Add(new RowDefinition());
dynamicGrid.ColumnDefinitions.Add(new ColumnDefinition());
dynamicGrid.ColumnDefinitions.Add(new ColumnDefinition());
var label = new Label();
var entry= new Entry();
dynamicGrid.Children.Add(label, 0, 0);
dynamicGrid.Children.Add(entry, 1, 0);
Upvotes: 0
Reputation:
The Grid gOut
is a local variable to your CreateDummyGrids
method and not passed to anywhere else. So after the method it'll just get destroyed.
You need to have somekind of element in your XAML to add the grid to (or just place the grid there and add the children directly to that).
So in the place where you want the grid to appear add something like this:
<Grid x:Name="productGrid" />
And change your CreateDummyGrids
to this:
public void CreateDummyGrids()
{
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.ColumnDefinitions.Add(new ColumnDefinition());
productGrid.ColumnDefinitions.Add(new ColumnDefinition());
for (int rowIndex = 0; rowIndex < 3; rowIndex++)
{
for (int columnIndex = 0; columnIndex < 2; columnIndex++)
{
var label = new Label
{
Text ="Hello",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
productGrid.Children.Add(label, columnIndex, rowIndex);
}
}
}
Now keep in mind that everytime you call this method new ColumnDefinitions, RowDefinitions and Labels will be added, so if you want you want to keep adding stuff you have to change the setup a bit. But I hope this is enough to get you in the right direction
Upvotes: 5