2015-04-28 154 views
0

我有下面的代码来使用for循环生成标签,但是for循环存在问题,如果productList有4个项目,它会生成1个标签而不是4个。解决问题是什么。C#动态生成标签

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)); 
    } 
} 
+0

哪个列表? carlist或productList? –

+0

在问题中,当你说“如果列表中有4个项目”,“列表”是指productList还是carList? –

+0

@LeonBambrick对于carList的每个增量,productList用新数据更新并生成一个新标签,直到carList完成。 – PRCube

回答

4

这仅依赖于我,不是记者:

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

所以,你可能会在其他的顶部绘制标签之一。 在这种情况下,你需要添加J任务到组合,例如像这样:

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

我也会改变你引用的标签的方式。 (我无法从上下文中判断你所做的事情是否可行,因为它取决于productLabels变量是如何实例化的。)

+0

就在我的代码上方,这是我如何声明标签。 ArrayList productLabels = new ArrayList(); – PRCube

+1

而是添加一个新变量,告诉添加的标签的编号并使用它来计算位置,因为它们可能仍然重叠。而引用List中的标签绝对是错误的。 –