如何动态生成在字典中显示值的标签

时间:2012-07-23 06:14:37

标签: c# dictionary label dynamically-generated

我想在单独的标签中显示字典中的值。我得到这样的字典:

Dictionary<string, int> counts = new Dictionary<string, int>();
foreach (string code in myCodeList)
{
    if (!counts.ContainsKey(code))
    {
       counts.Add(code, 1);
    }
    else
    {
       counts[code]++;
    }
}

//now counts contains the expected values

我想动态生成标签,因为counts中的元素只能在运行时确定。

2 个答案:

答案 0 :(得分:2)

Dictionary<string, int> counts = new Dictionary<string, int>();
foreach (string code in myCodeList)
{
    if (!counts.ContainsKey(code))
    {
       counts.Add(code, 1);
    }
    else
    {
       counts[code]++;
    }
}

Point p = new Point(12, 12); //initial location - adjust it suitably
foreach (var item in counts)
{
    var label = new Label();
    label.Text = item.Key + " - " + item.Value;
    label.Location = new Point(p.X, p.Y);
    label.Tag = item; //optional
    Controls.Add(label);

    p.Y += label.Height + 6; //to align vertically
    //p.X += label.Width + 18; //to align horizontally. 
}

这是基本方法。您所要做的就是根据您的设计调整变量p以正确定位标签。

答案 1 :(得分:0)

这应该就够了

修改

YourLabel.Text = counts.Count.ToString();