0
votes

I have a TableLayoutPanel on a form which has 8 columns and 8 rows. I'm trying to populate this table from a list of a user controls which each contain three labels. When I run the app, I can see it has been populated, but looking at the actual form, it is empty.

I've tried replacing the control with just a label, and they show up fine, it's just when I try to use the user control that it doesn't work.

This code runs in the Load method and generates a list of GridSquareModel, which is used to populate the user control. Each model has an X and Y position which relates to their cell on the table panel.

var startup = new StartupForm();
if (startup.ShowDialog() == DialogResult.OK)
{
    var grid = new List<GridSquareModel>();
    for (int i = 0; i < 64; i++)
    {
        Position pos = new Position();
        pos.X = i % 8;
        pos.Y = i / 8;
        grid.Add(new GridSquareModel(pos));
    }

    RenderGrid(grid);
}
else
{
    Application.Exit();
}

This method generates a GridSquareControl for every GridSquareModel in the list. The X and Y value in the position determines which cell they are added to.

private void RenderGrid(List<GridSquareModel> grid)
{
    UIGrid.Clear();
    GridTable.Controls.Clear();

    foreach (var item in grid)
    {
        var control = new GridSquareControl(item)
        {
            Dock = DockStyle.Fill
        };
        GridTable.Controls.Add(control, item.Position.X, item.Position.Y);
        //GridTable.Controls.Add(new Label
        //{
        //    Text = "TEST"
        //}, item.Position.X + 1, item.Position.Y + 1);
    }

}

I have commented my attempt to replace the GridSquareModel with a Label, which worked. This should produce a table containing 64 controls but once it is loaded the table appears empty.

1
If Label works and GridSquareControl does not, I would suspect that control itself. For example is it's Visible set to true? It is hard to investigate/help when we do not know exactly how is GridSquareControl implemented. - Stano Peťko

1 Answers

0
votes

I'm an idiot. I created a constructor for GridSquareControl but it did not include the InitializeComponent method, so obviously it was not rendered. All is working as expected now.