如何动态命名Linklabels?

问题描述 投票:-1回答:2

我试图动态更改链接标签的名称,以便能够通过for statment循环它们,但由于我缺乏编程知识,我无法完成它。

如果你能解释每一步,我会非常感激。

for (int i = 0; i < 205; i++)
{
    if (LinkLabel# + i.Text == "name")
    {
        // do stuff

    }
}
c# winforms
2个回答
0
投票

您可以按名称搜索表单上的控件以获取对它们的引用。

LinkLabel ll = (LinkLabel)this.Controls["LinkLabel" + i];

如果转换失败或未找到控件,这可能会抛出异常。

更安全的方法是使用模式匹配:

if (this.Controls["LinkLabel" + i] is LinkLabel ll)
{
    // do stuff with ll
}

0
投票

另一种方法(由@Broots Waymb建议)将动态创建链接标签控件并将它们添加到表单中。下面是一些示例代码,我从其他已经使用的代码中对其进行了调整。 (未经测试,但看起来应该可以使用)

    /// <summary>
    /// List for storing references to the LinkLabels
    /// </summary>
    List<LinkLabel> m_LinkLabels = new List<LinkLabel>();

    /// <summary>
    /// Creates and places all the LinkLabels on the form
    /// </summary>
    private void CreateLinkLabels()
    {
        int startingX = 100;        // starting top left X coordinate for first link label
        int startingY = 100;        // starting top left Y coordinate for first link label
        int xOffset = 20;           // horizontal space between labels
        int yOffset = 20;           // vertical space between labels
        int labelsToCreate = 100;   // total number of labels to create
        int labelsPerRow = 10;      // number of labels in each row
        int labelWidth = 61;        // width of the labels
        int labelHeight = 13;       // height of the labels

        int labelsInCurrentRow = 0; // number of labels in the current row
        int x = startingY;          // current x coordinate
        int y = startingX;          // current y coordinate
        int tabIndexBase = 65;      // base number for tab indexing 

        for (int i = 0; i < labelsToCreate; i++)
        {
            // update coordinates for next row
            if (labelsInCurrentRow == labelsPerRow)
            {
                x = startingX;
                y += yOffset;
                labelsInCurrentRow = 0;
            }
            else
            {
                x += xOffset;
                labelsInCurrentRow++;
            }

            // create the label
            LinkLabel ll = new LinkLabel()
            {
                Name = "LinkLabel" + (i + 1), // +1 to correct zero based index
                AutoSize = true,
                Location = new System.Drawing.Point(x, y),
                Size = new System.Drawing.Size(labelWidth, labelHeight),
                TabIndex = tabIndexBase + i,
                TabStop = true,
                Text = "LinkLabel" + (i + 1) // +1 to correct zero based index
            };

            // add the label to the list
            m_LinkLabels.Add(ll);
        }

        // add all controls in the list to the form
        this.Controls.AddRange(m_LinkLabels.ToArray());
    }
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.