从字典创建标签

时间:2016-03-08 15:24:35

标签: c# winforms dictionary

我有一个带有GroupBox的winform,我想在运行时动态创建标签。我为function copyToClipboard(text) { if (window.clipboardData) { // Internet Explorer window.clipboardData.setData("Text", text); } else { unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper); clipboardHelper.copyString(text); } } Dictionary<string, string>使用了label.Name。也许还有更好的方法,我愿意接受。我确实得到了第一个label.Text来正确写出来,而不是其他的。建议?

这是我的字典:

label

以下是我使用的方法:

public static Dictionary<string, string> LabelTexts = new Dictionary<string, string>()
{
    {"lblInstructions1", "Instructions 1." },
    {"lblInstructions2", "Instructions 2." },
    {"lblInstructions3", "Instructions 3." },
    {"lblInstructions4", "Instructions 4." },
    {"lblInstructions5", "Instructions 5." },
    {"lblInstructions6", "Instructions 6." },
    {"lblInstructions7", "Instructions 7." },
};

2 个答案:

答案 0 :(得分:1)

您为所有标签提供相同的位置:

l.Location = new Point(0, l.Bottom + 5);

相反,在这些方法之外放置一个变量来记住最后一个值并每次递增它:

private void CreateLabelsForTesting(GroupBox grpBoxInstructions)
{    
    // This will remember the last position between loops
    var lastPos = 0;

    foreach (KeyValuePair<string, string> labels in LabelTexts)
    {
        Label l = new Label();
        l.Name = labels.Key;
        l.Text = labels.Value;                
        l.Size = new Size(130, 12);                
        l.Location = new Point(0, lastPos);

        lastPos += 15; // Adds 15 to the previous value

        grpBoxInstructions.Controls.Add(l);
    }
}

因此,在第一个循环中,lastPos等于0,标签将位于顶部。如果您愿意,可以将其设置为大于0的值,这只是一个示例 在第一个循环之后,lastPos现在为15,因此第二个标签将进一步减少15个像素。然后是30岁,然后是45岁等等......

答案 1 :(得分:0)

private void CreateLabelsForTesting(GroupBox grpBoxInstructions)
{
    int x = 0;
    int y = 0;

    foreach (KeyValuePair<string, string> labels in LabelTexts)
    {
        Label l = new Label();
        l.Name = labels.Key;
        l.Text = labels.Value;                
        l.Size = new Size(130, 12);    

        x += 0;
        y += l.Height + 5;       

        l.Location = new Point(x, y);

        grpBoxInstructions.Controls.Add(l);
    }
}