c#

C#中如何实现单选框

小樊
104
2024-08-08 20:22:41
栏目: 编程语言

在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事件关联一个事件处理方法来实现当选择某个单选框时弹出消息框显示选项内容。

0
看了该问题的人还看了