C#动态生成标签

时间:2015-04-28 05:22:04

标签: c# for-loop dynamic-controls

我有以下代码使用for循环生成标签,但是for循环有问题,如果productList有4个项目,它会生成1个标签而不是4个。我无法弄清楚是什么问题是。

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

1 个答案:

答案 0 :(得分:4)

这只依赖于i,而不是j:

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    NSArray *arr = appDelegate.navController.viewControllers;

    for (UIViewController *vc in arr) {
        if (vc isKindOfClass:[CompareViewController class]) {
            CompareViewController *cvc = (CompareViewController *)vc;
            [cvc.btn setTitle:@"Hello" forState:UIControlStateNormal];
            break;
        }
    }

所以你可能会将标签一个放在另一个上面。 在这种情况下,您需要在混合中添加j,例如:

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

我也会改变你引用标签的方式。 (我不能从上下文中判断出你正在做什么是好的,因为它取决于productLabels变量的实例化方式。)