Skip to main content
 首页 » 编程设计

c#之如何在消息框上显示,选择了哪个单选按钮

2024年02月20日15findumars

我有 2 个性别单选按钮。一名男性(名为 radMale)一名女性(名为 radFemale)。假设用户单击“男性”按钮。我如何在 MessageBox 上显示他选择的内容?

MessageBox.Show(radMale = "Male"); 

我知道这行不通,有人知道哪个代码行吗?

请您参考如下方法:

我尝试执行以下代码,这可能会解决您的问题。

public partial class Form1: Form 
{ 
        public Form1() 
        { 
            InitializeComponent(); 
            this.Load += new EventHandler(Form1_Load); 
            radioButton1.CheckedChanged += new EventHandler(radioButton_CheckedChanged); 
            radioButton2.CheckedChanged += new EventHandler(radioButton_CheckedChanged); 
        } 
 
        void radioButton_CheckedChanged(object sender, EventArgs e) 
        { 
            RadioButton rb = (RadioButton)sender; 
            if(rb.Checked) 
                MessageBox.Show(rb.Text); //Shows whatever Text your radiobutton has 
        } 
 
        void Form1_Load(object sender, EventArgs e) 
        { 
 
        } 
}