在C#中,可以使用RadioButton控件來實現單選框。以下是一個簡單的示例代碼:
using System;
using System.Windows.Forms;
public class MainForm : Form
{
private RadioButton radioButton1;
private RadioButton radioButton2;
public MainForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.radioButton1 = new RadioButton();
this.radioButton1.Text = "Option 1";
this.radioButton1.Location = new System.Drawing.Point(50, 50);
this.Controls.Add(this.radioButton1);
this.radioButton2 = new RadioButton();
this.radioButton2.Text = "Option 2";
this.radioButton2.Location = new System.Drawing.Point(50, 80);
this.Controls.Add(this.radioButton2);
this.radioButton1.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
this.radioButton2.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
MessageBox.Show("Selected option: " + radioButton.Text);
}
}
public static void Main()
{
Application.Run(new MainForm());
}
}
在上面的示例中,創建了兩個RadioButton控件并添加到窗體中。然后通過給每個單選框的CheckedChanged事件關聯一個事件處理方法來實現當選擇某個單選框時彈出消息框顯示選項內容。