Search code examples
c#for-loopdynamic-controls

C# Generating Labels Dynamically


I have got the below code to generate labels using for loop, however there is a problem with the for loop, if the productList has 4 items, it generates 1 label instead of 4. I can't figure out what the problem is.

List<models.Car> carList = carController.getCars();    
for (int i = 0; i < carList.Count; i++) 
{
    List<models.Product> productList = productController.getProducts(carList[i].Model);

    for (int j = 0; j < productList.Count; j++) 
    {
        productLabels.Add(new Label());
        var productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50);
        (productLabels[j] as Label).Location = productLabelsPoint;
        (productLabels[j] as Label).Size = new System.Drawing.Size(150, 15);
        (productLabels[j] as Label).Text = productList[j].Title;
        this.Tab.TabPages["tab1"].Controls.Add((productLabels[j] as Label));
    }
}

Solution

  • This only relies on i, not on j:

    System.Drawing.Point productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50);
    

    So you might be drawing the labels one on top of the other. In which case, you'd need to add j into the mix, for example like this:

    System.Drawing.Point productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50 + j * 50);
    

    I would also change the way you are referencing the label. (I can't tell from the context if what you are doing is okay or not, as it depends how that productLabels variables has been instantiated.)