0

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));
    }
}
8
  • which list? the carlist or the productList? Commented Apr 28, 2015 at 5:24
  • In the question, when you say "if the list has 4 items" does 'the list' mean productList or carList ? Commented Apr 28, 2015 at 5:27
  • @LeonBambrick for each increment of carList, productList is updated with new data and generates a new labels until the carList is finished. Commented Apr 28, 2015 at 5:28
  • Ok @PRCube. I hear what you're saying. Now stick with me here. I have a question about your question. There is something that I cannot understand. I need to know the answer here, when you say "if the list has 4 items".... it's a good example... but I don't know what it means by 'the list'. Commented Apr 28, 2015 at 5:30
  • @LeonBambrick I ment the productList, which is used as the number of labels to generate. so productList.Count = number of labels needed. Commented Apr 28, 2015 at 5:33

1 Answer 1

4

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

just above my code, this is how I declare the labels. ArrayList productLabels = new ArrayList();
Rather add a new variable telling the number of the label added and use that to calculate the position, since they might still overlap. And the referencing the label from the List was definitely wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.