首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

C#需要动态创建单选按钮并确定用户在Winform中选择的值

在Winform中,可以使用C#动态创建单选按钮并确定用户选择的值。以下是一个简单的示例代码:

代码语言:csharp
复制
using System;
using System.Windows.Forms;

namespace DynamicRadioButtons
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CreateRadioButtons();
        }

        private void CreateRadioButtons()
        {
            RadioButton radioButton1 = new RadioButton();
            radioButton1.Text = "Option 1";
            radioButton1.Location = new System.Drawing.Point(10, 10);
            radioButton1.Name = "radioButton1";
            radioButton1.Size = new System.Drawing.Size(104, 24);
            radioButton1.TabIndex = 0;
            radioButton1.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
            this.Controls.Add(radioButton1);

            RadioButton radioButton2 = new RadioButton();
            radioButton2.Text = "Option 2";
            radioButton2.Location = new System.Drawing.Point(10, 40);
            radioButton2.Name = "radioButton2";
            radioButton2.Size = new System.Drawing.Size(104, 24);
            radioButton2.TabIndex = 1;
            radioButton2.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
            this.Controls.Add(radioButton2);

            RadioButton radioButton3 = new RadioButton();
            radioButton3.Text = "Option 3";
            radioButton3.Location = new System.Drawing.Point(10, 70);
            radioButton3.Name = "radioButton3";
            radioButton3.Size = new System.Drawing.Size(104, 24);
            radioButton3.TabIndex = 2;
            radioButton3.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
            this.Controls.Add(radioButton3);
        }

        private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton radioButton = sender as RadioButton;
            if (radioButton.Checked)
            {
                MessageBox.Show("You selected: " + radioButton.Text);
            }
        }
    }
}

在这个示例中,我们创建了三个单选按钮,并将它们添加到窗体上。当用户选择一个单选按钮时,会触发radioButton_CheckedChanged事件,并显示一个消息框,显示用户选择的值。

注意:在实际应用中,可以根据需要动态创建单选按钮,并将它们添加到窗体上。这个示例仅用于演示如何创建和处理单选按钮的选择事件。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券