using System;
using System.Windows.Forms;
namespace RadioButtonExample
{
public class Form1 : Form
{
private GroupBox groupBox1;
private RadioButton radioButton1;
private RadioButton radioButton2;
private Label label1;
public Form1()
{
// Initialize components
this.groupBox1 = new GroupBox();
this.radioButton1 = new RadioButton();
this.radioButton2 = new RadioButton();
this.label1 = new Label();
// Set properties for groupBox1
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Size = new System.Drawing.Size(200, 100);
this.groupBox1.Text = "Choose an option";
// Set properties for radioButton1
this.radioButton1.Location = new System.Drawing.Point(6, 20);
this.radioButton1.Size = new System.Drawing.Size(80, 20);
this.radioButton1.Text = "Option 1";
this.radioButton1.CheckedChanged += new EventHandler(this.RadioButton_CheckedChanged);
// Set properties for radioButton2
this.radioButton2.Location = new System.Drawing.Point(6, 50);
this.radioButton2.Size = new System.Drawing.Size(80, 20);
this.radioButton2.Text = "Option 2";
this.radioButton2.CheckedChanged += new EventHandler(this.RadioButton_CheckedChanged);
// Set properties for label1
this.label1.Location = new System.Drawing.Point(12, 120);
this.label1.Size = new System.Drawing.Size(200, 20);
this.label1.Text = "No option selected";
// Add controls to groupBox1
this.groupBox1.Controls.Add(this.radioButton1);
this.groupBox1.Controls.Add(this.radioButton2);
// Add controls to form
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label1);
// Set form properties
this.Text = "RadioButton Example";
this.Size = new System.Drawing.Size(250, 200);
}
private void RadioButton_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label1.Text = "You selected Option 1";
}
else if (radioButton2.Checked)
{
label1.Text = "You selected Option 2";
}
else
{
label1.Text = "No option selected";
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
System
和 System.Windows.Forms
命名空间,并定义了一个名为 Form1
的类,继承自 Form
类。GroupBox
、两个 RadioButton
和一个 Label
控件,并设置了它们的属性。RadioButton
的 CheckedChanged
事件添加了事件处理程序 RadioButton_CheckedChanged
,当选择改变时更新 Label
文本。Main
方法是应用程序的入口点,创建并运行 Form1
实例。这个示例展示了如何在 Windows Forms 应用程序中使用 RadioButton
控件,并根据用户的选择更新界面。
上一篇:c#创建数组
下一篇:c#排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站