首页 > 编程笔记 > C#笔记 阅读:3

C# GroupBox分组框的用法(附带实例)

如果读者已经掌握了单选按钮 RadioButton,单选按钮的特性是一次只能选取一个选项,假设现在要设计性别选项和学历选项两组选项,因为每一个组别必须有一项被选取,所以这时会产生问题。碰上这类问题,可以使用容器 GroupBox 分组框。

将每一个组别放在一个分组框中,这时会产生区分效果,每一个组别可以有一项被选取。此外,一个窗体如果有多个控件,使用容器将功能相同的控件归类,也可以让窗体有美观的效果。

使用 GroupBox 时需留意,创建 GoupBox 后,将所创建的单选按钮拖曳至 GroupBox 内,然后拖曳 Groupbox 时,GroupBox 内的单选按钮可以随之移动,这表示在 GroupBox 内创建单选按钮成功。

使用 GroupBox 容器时,常使用的属性是 Text,这可以设定容器的标题。

【实例】容器 GroupBox 分组单选按钮的应用,在这个实例中,读者可以选择不同组别的选项,单击“确定”按钮后可以输出选项。


控件 名称 (Name) 标题 (Text) 大小 (Size) 位置 (Location)
Form Form1 ch (600, 360) (0, 0)
Label label1 个人数据调查表 (136, 23) (222, 36)
GroupBox groupBox1 性别 (145, 150) (94, 73)
GroupBox groupBox2 婚姻状态 (145, 150) (344, 73)
RadioButton rdbMale 男性 (71, 27) (26, 45)
RadioButton rdbFemale 女性 (71, 27) (26, 92)
RadioButton rdbMarried 已婚 (71, 27) (37, 45)
RadioButton rdbUnmarried 未婚 (71, 27) (37, 92)
Button button1 确定 (112, 34) (233, 251)
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        rdbMale.Checked = true;  // 预选 男性
        rdbMarried.Checked = true; // 预选 已婚
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string msgSex = string.Empty;
        string msgMarried = string.Empty;
        if (rdbMale.Checked)
        {
            msgSex = "男性";
        }
        if (rdbFemale.Checked)
        {
            msgSex = "女性";
        }
        if (rdbMarried.Checked)
        {
            msgMarried = "已婚";
        }
        if (rdbUnmarried.Checked)
        {
            msgMarried = "未婚";
        }
        MessageBox.Show("你是" + msgSex + msgMarried, "ch");
    }
}
执行结果为:

相关文章