c# - 以编程方式创建 GroupBox 并在其中添加标签

标签 c# winforms

我想以编程方式创建一个组框,并在其中放置标签。现在我创建了这个,但经过设计,我有这样的:

enter image description here

我正在尝试,但我不知道如何将标签分配到正确的位置以及如何将其分配给特定的组框

GroupBox groupBox1 = new GroupBox();
Panel grid1 = new Panel();
Label lbl1 = new Label { Text = "Completed" };
Label lbl2 = new Label { Text = "label" };
Label lbl3 = new Label { Text = "In progress" };
Label lbl4 = new Label { Text = "label" };
//etcetera
groupBox1.Width = 185;
groupBox1.Height = 160;
grid1.Height = 185;
grid1.Width = 160;

我怎样才能实现这一目标?问候 更新

正如下面的评论,我尝试

GroupBox groupBox1 = new GroupBox();
                    this.Controls.Add(groupBox1);
                    Panel grid1 = new Panel();
                    groupBox1.Controls.Add(grid1);
                    groupBox1.Location = new Point(20, 250);
                    grid1.Location = new Point(20, 250);
                    Label lbl1 = new Label { Text = "test" };
                    Label lbl2 = new Label { Text = "Test2" };
                    groupBox1.Name = "TESTTT";
                    groupBox1.Width = 222;
                    groupBox1.Height = 149;

                    grid1.Height = 218;
                    grid1.Width = 145;
                    grid1.Controls.Add(lbl1);
                    grid1.Controls.Add(lbl2);

结果: enter image description here

但是我的组框只是清除,没有名称和标签,为什么会发生这种情况?

最佳答案

WinForms 中的控件经过排列,以便它们位于彼此内部。因此,您的 Form 有一个 Controls 集合,它本质上是 Control 类型的 Collection。因此,如果将 GroupBox 添加到表单,则必须将其添加到表单的 Controls 集合中。然后,如果您将控件添加到 GroupBox 中,则需要将其添加到 GroupBox 控件集合中。

考虑到这一点,您可以执行以下操作:

private void AddGroupBoxAndLables()
{
    GroupBox groupBox1 = new GroupBox();
    groupBox1.SetBounds(50, 50, 300, 200);
    this.Controls.Add(groupBox1);

    Label lblCompleted = new Label { Name = "lblCompleted", Text = "Completed" };
    lblCompleted.Location = new Point(20, 20);
    groupBox1.Controls.Add(lblCompleted);
    Label valCompleted = new Label { Name = "valCompleted" };
    valCompleted.Location = new Point(80, 20);
    groupBox1.Controls.Add(valCompleted);

    Label lblInProgress = new Label { Name = "lblInProgress", Text = "In Progress" };
    lblInProgress.Location = new Point(20, 60);
    groupBox1.Controls.Add(lblInProgress);
    Label valInProgress = new Label { Name = "valInProgress" };
    valInProgress.Location = new Point(80, 60);
    groupBox1.Controls.Add(valInProgress);
}

关于c# - 以编程方式创建 GroupBox 并在其中添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51993028/

相关文章:

c# - Oxyplot:为 Oxyplot 的热图设置边距/填充

c# - Android 上的 Azure 通知中心。如何发送给特定用户?

c# - WinForm 和循环

c# - 在 C# 中更改时区

c# - 使用 IExcelDataReader 从 excel 中获取正确的文本显示

c# - 在 wpf 中快速生成 ViewModel 属性?

c# - 圆边面板

c# - DataGridView 在左键单击时保持选中多行

c# - Windows 窗体 StatusStrip 控件中的纯图像

winforms - DataGridViewImageColumn 红色 x