【问题标题】:How to dynamically generate labels which displays values in a dictionary如何动态生成在字典中显示值的标签
【发布时间】:2012-07-24 18:30:56
【问题描述】:

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

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 中的元素只能在运行时确定。

【问题讨论】:

  • 我没有得到你的代码,为什么不只是 Label.Text=String.Concat(",",myList);

标签: c# dictionary label dynamically-generated


【解决方案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]++;
    }
}

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

【讨论】:

  • 嗨,nawfal,谢谢你,所以我想在单独的标签 VPUDB - 11 和 VPULN - 9 中显示,我需要动态显示它,假设它也可能包含 3 或 4 个标签。
  • @chitra 您希望将这些值列在一个标签中,还是希望每个字符串显示在单独的标签中?
  • 单独的标签,但标签应该是动态的,假设我的字符串数组可能包含 3 或 4 个代码...取决于我的字符串输入
  • @so 你的意思是如果字符串数组中有 4 个字符串,那么你需要将这 4 个字符串显示在 4 个单独的标签中?
  • 对不起,S,如果 4 表示 4 个标签
【解决方案2】:

应该够了

编辑

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2019-01-31
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2016-05-28
    相关资源
    最近更新 更多