如何在 C# 中设置 GroupBox 的大小?

如何在 C# 中设置 GroupBox 的大小?

在 Windows 窗体中,GroupBox 是一个容器,其中包含多个控件,并且这些控件相互关联。或者换句话说,GroupBox 是围绕一组具有合适的可选标题的控件的框架显示。或者 GroupBox 用于对组中的相关控件进行分类。在 GroupBox 中,您可以使用 Size 属性在表单中设置 GroupBox 的大小。此属性表示 GroupBox 的高度和宽度(以像素为单位)。您可以通过两种不同的方式设置此属性:

1。设计时:设置 GroupBox 的大小是最简单的方法,如下所示:

第 1 步:创建一个如下图所示的 windows 窗体:

Visual Studio -> 文件 -> 新建 -> 项目 -> WindowsFormApp

第 2 步:接下来,将 GroupBox 从工具箱拖放到如下图所示的表单中:

步骤 3:拖放后,您将进入 GroupBox 的属性并设置 GroupBox 的大小,如下图所示:

输出:

2。运行时:比上面的方法要复杂一些。在此方法中,您可以借助给定的语法以编程方式设置 GroupBox 的大小:

public System.Drawing.Size Size { get; set; }

这里,Size 表示 GroupBox 的高度和宽度,以像素为单位。以下步骤展示了如何动态设置 GroupBox 的大小:

第 1 步:使用 GroupBox 类提供的 GroupBox() 构造函数创建一个 GroupBox。// Creating a GroupBox

GroupBox gbox = new GroupBox();

第二步:创建GroupBox后,设置GroupBox类提供的GroupBox的Size属性。// Setting the size

gbox.Size = new Size(329, 94);

第 3 步:最后将此 GroupBox 控件添加到表单中,并使用以下语句在 GroupBox 上添加其他控件:// Adding groupbox in the form

this.Controls.Add(gbox);

and

// Adding this control

// to the GroupBox

gbox.Controls.Add(c2);

例子:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace WindowsFormsApp45 {

public partial class Form1 : Form {

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

// Creating and setting properties

// of the GroupBox

GroupBox gbox = new GroupBox();

gbox.Location = new Point(179, 145);

gbox.Size = new Size(329, 94);

gbox.Text = "Select Gender";

gbox.Name = "Mybox";

// Adding groupbox in the form

this.Controls.Add(gbox);

// Creating and setting

// properties of the CheckBox

CheckBox c1 = new CheckBox();

c1.Location = new Point(40, 42);

c1.Size = new Size(49, 20);

c1.Text = "Male";

// Adding this control

// to the GroupBox

gbox.Controls.Add(c1);

// Creating and setting

// properties of the CheckBox

CheckBox c2 = new CheckBox();

c2.Location = new Point(183, 39);

c2.Size = new Size(69, 20);

c2.Text = "Female";

// Adding this control

// to the GroupBox

gbox.Controls.Add(c2);

}

}

}

输出:

相关探索