我正在编写一个程序,从注册表获取数据,然后将组框添加到选项卡控件,并且在组框中我想创建与数据(键值对)一样多的标签控件(以显示注册表信息)我有。为此,我做了这个功能:

private void AddAllControl()
{
    GroupBox TestGroupBox = new GroupBox();
    TestGroupBox.AutoSize = true;
    TestGroupBox.Text = "valami";
    TestGroupBox.Height = 500;
    for (int i = 0; i < 21; i++)
    {
        Label TempLabel = new Label();
        TempLabel.Text = i.ToString();
        TempLabel.Location = new System.Drawing.Point(20 + i, 30);
        TempLabel.Show();
        TempLabel.Visible = true;
        TempLabel.Enabled = true;
        TestGroupBox.Controls.Add(TempLabel);               
    }
    tabPage_SandBox.Controls.Add(TestGroupBox);
}

当按下按钮时会处理此功能。之后,组框正确显示,但第一个标签(文本 = 0)仅出现 1 个标签,而不是 21 个标签。当我停止调试程序时,我看到所有标签都存在并且所有属性都正确,但它们没有出现。一定有什么我没注意到的地方。现在我的问题是?我做错了什么?正如你所看到的,我都尝试过 visibleenabled 财产,但都没有给我带来解决方案。

有帮助吗?

解决方案

你必须设置

  TempLabel.AutoSize = true;

你必须稍微修改一下位置

 TempLabel.Location = new System.Drawing.Point(20 + 10 * i, 30);

或者我认为您希望标签一个在另一个下面,所以您必须将位置设置为

 TempLabel.Location = new System.Drawing.Point(20, 20+20 * i);

其他提示

如果您的标签大小恒定,那么

TestGroupBox.Controls.Add(new Label()
{
    Text = i.ToString(),
    Location = new Point(20 + (i*20), 30),
    Size = new Size(20, 20)
});

会成功的

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top