Get Selected Radio button’s Text in C# windows app

本文介绍如何使用C#在Windows应用中通过代码获取单选按钮的选定文本,并在按钮点击时显示。提供了两种方法:传统方法和更高效的方法。传统方法涉及为每个单选按钮设置事件处理程序,而高效方法则创建了一个通用方法来获取选定的单选按钮文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The object is to get selected radio button’s text in windows app using C#. It can be done in many ways. Suppose you have one group box having radio-buttons. You have to show selected radio button’s text on OK button click.

 Get Selected Radio button’s Text in C# windows app

Method 1(Traditional Approach):

1. Write following code:

?
01
02
03
04
05
06
07
08
09
10
11
String selectedText;
 
private void radioButton_CheckedChanged( object sender, EventArgs e)
         {
            if (((RadioButton)sender).Checked)
             selectedText = ((RadioButton)sender).Text; 
         }
private void buttonOK_Click( object sender, EventArgs e)
         {
             MessageBox.Show(selectedText, "Selected Item" ); 
         }

2. Now, for each radio button, Goto properties events > give radioButton_CheckedChangedmethod name in CheckedChanged event and save it.

3. When you run app, select any option, radioButton_CheckedChanged is fired and text is stored in the variable and it is displayed in messagebox on button click.

I don’t like 2 step. Suppose you have many radio buttons then it is time consuming to set event for all. So, I prefer second method.


Method II:

In this method, I created a method GetSelectedRadioButtonText which accepts groupbox as a parameter and returns selected radio button’s text.

?
1
2
3
4
5
6
7
private string GetSelectedRadioButtonText(GroupBox grb) {
            return grb.Controls.OfType<RadioButton>().SingleOrDefault(rad => rad.Checked == true ).Text;  
         }
private void buttonOK_Click( object sender, EventArgs e)
         {
             MessageBox.Show(GetSelectedRadioButtonText(groupBox1), "Selected Item" ); 
         }

Hope, It helps.



转自:http://techbrij.com/get-selected-radio-button-text-windows-app-net

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值