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

被折叠的 条评论
为什么被折叠?



