繁体   English   中英

C#从包含类的ArrayList动态地在Form中创建标签

[英]C# creating labels in Form dynamically from an ArrayList containing Class

我有一个应该显示一些标签的程序(10-50)。 我想将值存储在数组中,以便对其进行迭代。 我发现了如何在ArrayList中存储不同的数据类型。 我有一个hdinfoData类,并将其分配给数组列表。 我以为我有一个像2D数组那样具有不同数据类型的东西。 我无法访问存储在数组列表中的值,因为它实际上不是2D数组,它只是一个包含对象的数组(hdinfoData类)

什么是正确的方法? 我想动态创建标签对“标签”“值”。 此外,我想更改顺序。

ArrayList hdiData = new ArrayList();

hdinfoData a = new hdinfoData();
   a.ID = 1;
   a.Label = "USER";
   a.Value = user;
   a.PosX = 1;
   a.PosY = 2;

hdiData.Add(a);

hdinfoData b = new hdinfoData();
   b.ID = 2;
   b.Label = "HOST";
   b.Value = host;
hdiData.Add(b);


Label[] lbl = new Label[hdiData.Count];

int y = 50;
for (int i = 0; i < hdiData.Count; i++)
{
   int x = 15;

   lbl[i] = new Label();
   lbl[i].Location = new System.Drawing.Point(x, y);
   lbl[i].Text = (string)hdiData[i];
   lbl[i].ForeColor = Color.White;

   Form1.Controls.Add(lbl[i]);
   y += 25;
}    

internal class hdinfoData
{  
 public int ID { get; set; }
 public string Label { get; set; }
 public string Value { get; set; }
 public int PosX { get; set; }
 public int PosY { get; set; }
}

您最好使用List<hdinfoData>而不是ArrayList 然后,只需像其他任何对象字段一样访问其元素的字段即可:

var hdiData = new List<hdinfoData>();
.................
    lbl[i].Text = hdiData[i].Label;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM