2015-04-28 25 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中的標籤絕對是錯誤的。 –