动态创建的C#标签不可见

时间:2019-07-31 01:44:13

标签: c# properties label

我正在尝试在动态生成的文本框旁边显示一些动态生成的标签。出现文本框,但标签不显示。

我研究了几种解决方案,并尝试确保定义了所有标签属性。我看了一些不必要的与线程相关的解决方案,因为我没有更改可见性状态,我只想弹出文本框旁边的标签。

TextBox[] channelNames = new TextBox[numOfChannels];
GroupBox channelBox = new GroupBox();
Label[] labelNames = new Label[numOfChannels];

for (int currentChannelIndex = 0; currentChannelIndex < numOfChannels; currentChannelIndex++)
{
    var txt = new TextBox();
    channelNames[currentChannelIndex] = txt;
    txt.Name = channelCollection[currentChannelIndex].PhysicalName;
    txt.Text = "ben";
    txt.Location = new Point(200, 32 + (currentChannelIndex * 28));
    txt.Visible = true;
    this.channelBox.Controls.Add(channelNames[currentChannelIndex]);

    var lbl = new Label();
    labelNames[currentChannelIndex] = lbl;
    lbl.AutoSize = true;
    lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
    lbl.Size = new Size(55, 13);
    lbl.TabIndex = 69;
    lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
    lbl.Location = new Point(175, 32 + (currentChannelIndex * 28));
    lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
    this.channelBox.Controls.Add(labelNames[currentChannelIndex]);
}

3 个答案:

答案 0 :(得分:0)

这里有几件事要检查:

1)您正在设置“自动尺寸”和“尺寸”。尝试删除“尺寸”

2)对于(55,13)大小,默认字体可能太大。
   尝试将字体显式设置为较小字体,以查看其是否显示。

答案 1 :(得分:0)

channelCollection[currentChannelIndex].PhysicalName是否实际上包含非空字符串?例如:

        class Something
        {
            public string PhysicalName { get; set; }
        }

        private void AddLabels()
        {
            Something[] channelCollection = new Something[]
            {
                //Applying this to Label.Text makes it "invisible"
                new Something() { PhysicalName = "" }
            };
            var currentChannelIndex = 0;

            var txt = new TextBox();
            txt.Name = channelCollection[currentChannelIndex].PhysicalName;
            txt.Text = "ben";
            txt.Location = new Point(200, 32);
            txt.Visible = true;
            this.Controls.Add(txt);

            var lbl = new Label();
            lbl.AutoSize = true;
            lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
            lbl.Size = new Size(55, 13);
            lbl.TabIndex = 69;
            lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
            lbl.Location = new Point(175, 32);
            lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.Controls.Add(lbl);
        }

答案 2 :(得分:0)

我实际上有一个例外,那就是导致该问题的此代码块的下游。我认为我会看到标签,因为在调用标签之后引发了异常。感谢您的建议。