C#中如何实现单选框

   2024-10-02 7710
核心提示:在C#中,可以使用RadioButton控件来实现单选框。以下是一个简单的示例代码:using System;using System.Windows.Forms;public cl

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号