2012-07-23 45 views
1

我想在单独的标签中的字典中显示值。我得到的解释是这样的:如何动态生成在字典中显示值的标签

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

我没有得到你的代码,为什么不只是Label.Text = String.Concat(“,”,myList); – Cynede 2012-07-23 06:18:22

回答

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即可正确定位标签。

+0

嗨,nawfal,谢谢你,所以我想要显示在单独的标签VPUDB - 11和VPULN - 9,我需要动态的,假设它也可能包含3或4个标签。 – chitra 2012-07-23 08:21:14

+0

@chitra是否希望将这些值列在一个标签中,或者希望每个字符串都显示在不同的标签中? – nawfal 2012-07-23 08:43:29

+0

单独的标签,但标签应该是动态的,假设,我的字符串数组可能包含3或4个代码......取决于我的字符串输入 – chitra 2012-07-23 08:51:24

0

这应该是足够了

编辑

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

这甚至不会编译。除了被错误的回答 – nawfal 2012-07-23 06:38:20